如果我在头文件中定义了一个全局变量(带初始化),并将该文件包含在两个文件中并尝试编译和链接,编译器会给出链接错误
headers.h:
#ifndef __HEADERS
#define __HEADERS
int x = 10;
#endif
Run Code Online (Sandbox Code Playgroud)
1.C:
#include "headers.h"
main ()
{
}
Run Code Online (Sandbox Code Playgroud)
2.C:
#include "headers.h"
fun () {}
Run Code Online (Sandbox Code Playgroud)
链接器抱怨,因为x一旦将所有目标文件放在一起创建可执行文件,就会有多个定义.您有两个不同的源文件,包括相同的头文件,并且该头文件定义了x一个值为10 的变量,因此最终得到两个定义x(一个在1.c中,另一个在2.c中).
要避免多个定义链接器错误,请将其放在头文件中(例如globals.h):
#ifndef GLOBALS_H
#define GLOBALS_H
/*
* The "extern" keyword means that this variable is accessible everywhere
* as long as this declaration is present before it is used. It also means
* that the variable x may be defined in another translation unit.
*/
extern int x;
#endif
Run Code Online (Sandbox Code Playgroud)
然后把它放在一个源文件中:
#include "globals.h"
int x = 10;
Run Code Online (Sandbox Code Playgroud)