在我的代码中,我有一些使用全局变量的无效函数。
int i =0;
void increment()
{
i++;
}
int main()
{
increment();
printf("i = %i\n",i)
}
我想将函数分离到不同的文件中,所以我移动了 int i;到头文件中,并在那里声明 void 函数。例如
(in my header file)
int i = 0;
void increment();
(in main file)
#include "header.h"
int main()
{
increment();
printf("i = %i\n",i);
}
当我编译时,我得到一个未定义的增量引用。我需要做什么来解决这个问题?
最佳答案
在你的头文件 myheader.h 中,
extern int i;
extern void increment();
在increment.c中,
#include "myheader.h"
void
increment()
{
i++;
}
在main.c中,
#include <stdio.h>
#include "myheader.h"
int i = 0;
int main()
{
increment();
printf("i = %i\n",i);
}
关于c - 在C中将函数分离到不同的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43691620/