C语言 如何将C程序拆分为多个文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5128664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:54:09  来源:igfitidea点击:

How to split a C program into multiple files?

ccodeblocks

提问by amin

I want to write my C functions in 2 separate .c files and use my IDE (Code::Blocks) to compile everything together.

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

How do I set that up in Code::Blocks?

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

How do I call functions in one .cfile from within the other file?

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

回答by Matteo Italia

In general, you should define the functions in the two separate .cfiles (say, A.cand B.c), and put their prototypes in the corresponding headers (A.h, B.h, remember the include guards).

通常,您应该在两个单独的.c文件(例如A.cB.c)中定义函数,并将它们的原型放在相应的头文件中(A.h, B.h,记住包含守卫)。

Whenever in a .cfile you need to use the functions defined in another .c, you will #includethe corresponding header; then you'll be able to use the functions normally.

每当在一个.c文件中你需要使用在另一个文件中定义的函数时.c,你就会#include相应的头文件;然后你就可以正常使用这些功能了。

All the .cand .hfiles must be added to your project; if the IDE asks you if they have to be compiled, you should mark only the .cfor compilation.

所有的.c.h文件都必须添加到您的项目中;如果 IDE 询问您是否必须编译它们,您应该只标记.cfor compiler。

Quick example:

快速示例:

Functions.h

函数.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

函数.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;
}