多文件编程的小例子
功能:在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_1_H
void mytool1_printf(char* print_str);
#endif
//mytool1.c
#include”mytool1.h”
#include<stdio.h>
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”<br><br>#include<stdio.h>
void mytool2_print(char* print_str)
{
printf(“This is mytool2 print %s\n”,print_str);
}
makefile:
cc=gcctarget=mainobj=main.o mytool1.o mytool2.o$(target):$(obj) $(cc) $(obj) -o $(target)main.o:main.c $(cc) -c main.cmytool1.o:mytool1.c $(cc) -c mytool1.cmytool2.o:mytool2.c $(cc) -c mytool2.cclean : $(RM) *.o $(target)
注:Makefile有三个非常有用的变量。分别是$@,$^,$<代表的意义分别是:
$@–目标文件,$^–所有的依赖文件,$<–第一个依赖文件。