如何避免这种链接错误? [英] how do i avoid this linking error?
问题描述
如果我已经在头文件中定义一个全局变量(与初始化),并包括在两种文件这个文件,并尝试编译和链接,编译器提供链接错误
headers.h:
的#ifndef __HEADERS
#定义__HEADERS
INT X = 10;
#万一
1.C:
的#includeheaders.h
main()的
{
}
2.C:
的#includeheaders.h
有趣的(){}
链接器抱怨因为会有的多个定义X
一旦它把所有的目标文件一起创建可执行文件。你有两个不同的源文件,包括相同的头文件,该头文件定义了一个变量 X
具有值10,所以你最终与<$ C的两个定义$ C> X (一个在1.C,另一个在2.C)。
要避免多重定义链接错误,把它放在一个头文件(例如 globals.h
)
的#ifndef GLOBALS_H
#定义GLOBALS_H/ *
*在外部关键字意味着这个变量是可访问的无处不在
*只要这个声明是$ P $ psent使用前。这也意味着
*变量x可以在另一翻译单元来定义。
* /
EXTERN INT X;#万一
然后把这个有一个源文件:
的#includeglobals.hINT X = 10;
if i have defined a global variable(with initialization) in header file, and included this file in two file and try to compile and link, compiler gives linking error
headers.h:
#ifndef __HEADERS
#define __HEADERS
int x = 10;
#endif
1.c:
#include "headers.h"
main ()
{
}
2.c:
#include "headers.h"
fun () {}
The linker complains because there will be multiple definitions of x
once it puts all the object files together to create the executable. You have two different source files including the same header file, and that header file defines a variable x
having a value of 10, so you end up with two definitions of x
(one in 1.c and another in 2.c).
To avoid multiple definition linker errors, put this in a header file (for example 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
Then put this in one source file:
#include "globals.h"
int x = 10;
这篇关于如何避免这种链接错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!