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

发布于 2024-10-19 21:40:28 字数 147 浏览 1 评论 0原文

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

如何在 Code::Blocks 中进行设置?

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧梦荧光笔 2024-10-26 21:40:28

一般来说,您应该在两个单独的 .c 文件中定义函数(例如 AcBc),并将它们的原型放在相应的标头(AhBh,记住包含防护)。

每当在 .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;
}

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

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

All the .c and .h files must be added to your project; if the IDE asks you if they have to be compiled, you should mark only the .c for compilation.

Quick example:

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文