利用预编译解决 C/C++重复定义的错误¶
我们现在有main.c和function.h两个文件
| main.c | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
| function.h | |
|---|---|
1 2 3 4 5 6 7 | |
我们使用命令gcc main.c -o hello,再使用ls,可以看到当前目录下已经生成了hello.exe
然后我们再使用命令.\hello.exe运行程序,.\表示当前目录
到目前为止都没什么不对的地方,现在我们添加一个function2.h,并在main.c中引入function2.h
function2.h的内容如下
function2.h
#include "function.h"
main.c引入部分修改为
| main.c | |
|---|---|
1 2 3 4 | |
我们再次使用命令gcc main.c -o hello,发现出现了报错信息 redefinition
意思就是重复定义了变量 A,那么我们需要在function.h中加入预编译指令#ifndef #define #endif,
这样可以有效防止重复定义或者重复包含的问题,我们将function.h中的三条预编译指令解注释
function.h修改为
| function.h | |
|---|---|
1 2 3 4 5 6 7 | |
我们再次使用命令gcc main.c -o hello,发现编译正确通过了,再次运行程序
结果正确,因此在规范的开发当中我们需要使用#ifndef #define #endif 来防止重复定义的问题



