如何将C程序拆分成多个文件?

ami*_*min 41 c codeblocks

我想在两个单独的.c文件中编写我的C函数,并使用我的IDE(Code :: Blocks)将所有内容编译在一起.

如何在Code :: Blocks中设置它?

如何.c从另一个文件中调用一个文件中的函数?

Mat*_*lia 109

在一般情况下,你应该定义在两个单独的函数.c的文件(比如,A.cB.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)

  • `#ifdef` /`#define` /`#endif`用于避免在多个包含相同标题的情况下出现问题.看一下维基百科上关于[包括警卫](http://en.wikipedia.org/wiki/Include_guard)的页面 - 这里都有解释.顺便说一句,既然我的答案解决了你的问题,你可以考虑将其标记为已接受(谢谢!).`:)` (4认同)
  • @learner 不幸的是,这取决于您正在使用的确切 IDE/构建系统,所以我认为我无法轻松添加它。最终,最好将其留给针对每个构建系统的特定答案。 (2认同)