ami*_*min 41 c codeblocks
我想在两个单独的.c文件中编写我的C函数,并使用我的IDE(Code :: Blocks)将所有内容编译在一起.
如何在Code :: Blocks中设置它?
如何.c从另一个文件中调用一个文件中的函数?
Mat*_*lia 109
在一般情况下,你应该定义在两个单独的函数.c的文件(比如,A.c和B.c),并把他们的原型在相应的报头(A.h,B.h,记得包括警卫).
每当在一个.c文件中你需要使用另一个中定义的函数时.c,你就会#include得到相应的标题; 那么你将能够正常使用这些功能.
所有.c和.h文件必须添加到您的项目中; 如果IDE询问您是否必须编译,则应仅标记.cfor compilation.
快速举例:
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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)