通常,您应该在两个单独的.c文件(例如,A.c和B.c)中定义函数,并将它们的原型放在相应的头文件中(A.h,B.h,记住
include guards).
每当在.c文件中你需要使用另一个.c中定义的函数时,你将#include相应的头文件;那么你将能够正常使用这些功能.
必须将所有.c和.h文件添加到项目中;如果IDE询问您是否必须编译,则应仅标记.c进行编译.
快速举例:
Functions.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
/* ^^ these are the include guards */
/* Prototypes for the functions */
/* Sums two ints */
int Sum(int a, int b);
#endif
Functions.c
/* In general it's good to include also the header of the current .c,
to avoid repeating the prototypes */
#include "Functions.h"
int Sum(int a, int b)
{
return a+b;
}
MAIN.C
#include "stdio.h"
/* To use the functions defined in Functions.c I need to #include Functions.h */
#include "Functions.h"
int main(void)
{
int a, b;
printf("Insert two numbers: ");
if(scanf("%d %d", &a, &b)!=2)
{
fputs("Invalid input", stderr);
return 1;
}
printf("%d + %d = %d", a, b, Sum(a, b));
return 0;
}