如何将C程序拆分为多个文件? [英] How to split a C program into multiple files?
问题描述
我想在2个独立的.c文件中编写C函数,并使用我的IDE(代码:: Blocks)将所有内容一起编译。
I want to write my C functions in 2 separate .c files and use my IDE (Code::Blocks) to compile everything together.
如何设置
如何从另一个文件中调用一个 .c
文件中的函数文件?
How do I call functions in one .c
file from within the other file?
推荐答案
通常,您应该在两个单独的 .c $中定义函数。 c $ c>个文件(例如
Ac
和 Bc
),然后将其原型放在相应的标头( Ah
, Bh
,请记住包括警卫)。
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).
无论何时在 .c
文件中,使用另一个 .c
中定义的函数,您将 #include
相应的标头;那么您将能够正常使用这些功能。
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.
所有 .c
和 .h
文件必须添加到您的项目中;如果IDE询问您是否必须对其进行编译,则应仅将 .c
标记为可编译。
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.
快速示例:
Functions.h
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
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
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;
}
这篇关于如何将C程序拆分为多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!