c - 在C中将函数分离到不同的文件中

标签 c function

在我的代码中,我有一些使用全局变量的无效函数。

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/

相关文章:

mysql - Windows 下最基本的 MySQL UDF 代码

查询。 Fn.Function 导致其他函数失效?

swift - 数组搜索功能在 Swift 中不起作用

python - 如何按特定列分配新的值列?

C++ 通过引用传递——这可以做到吗?

c - OpenMP - 为什么比较次数会减少?

c++ - 堆与栈之间的距离

c - 两种不同的输出

c - 为什么这个函数会出现段错误?

c - 使用c中的函数确定数组的最大值