由于在C语言中,不能把所有的代码都放在一个.c文件里面,这样这个.c文件会很大,而且代码维护起来会很麻烦。
于是在网上找了些C语言多文件编程的示例,记录下我的学习过程。
我们可以把我们的代码按功能进行划分,一些源文件存放函数的实现,一些头文件声明这些函数,这样代码会更有条理。
头文件的大致格式:
#ifndef _ABC_H_
#define _ABC_H_
//以上代码是为了防止这个头文件被多次包含,确保名字唯一
//宏定义
#define _MAX 100
//结果体声明
typedef struct{
int a;
}ABC;
//函数声明
void abcfun(void);
...
#endif
接下来介绍下多文件编程的小例子
功能:在main.c里面调用其他两个源文件里面的函数,然后输出字符串。
1、main.c
#include"mytool1.h"
#include"mytool2.h"
int main(int argc,char** argv)
{
mytool1_printf("hello.");
mytool2_print("hello");
return 1;
}
2、 mytool1.h mytool1.c
//mytool1.h
#ifndef _MYTOOL_1_H
#define _MYTOOL_2_H
void mytool1_printf(char* print_str);
#endif
//mytool1.c
#include"mytool1.h"
#include
void mytool1_printf(char* print_str)
{
printf("This is mytool1 print %s\n",print_str);
}
3、 mytool2.h mytool2.c
//mytool2.h
#ifndef _MYTOOL_2_H
#define _MYTOOL_2_h
void mytool2_print(char* print_str);
#endif
//mytool2.c
#include "mytool2.h"
#include
void mytool2_print(char* print_str)
{
printf("This is mytool2 print %s\n",print_str);
}
在linux下,把这几个文件放在同一个目录下,然后在shell中输入
gcc -c main.c
gcc -c mytool1.c
gcc -c mytool2.c
gcc -o main main.o mytool1.o mytool2.o
就可以生成可执行文件 main
关于 Makefile 还没学清楚,学清楚了补充。
引用:
http://blog.163.com/m13591120447_1/blog/static/21637918920132365724538/
http://soft.chinabyte.com/os/12/11584512.shtml
原文:http://www.cnblogs.com/tqianly/p/4374735.html