C语言 ... 链接器错误的多重定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17764661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple definition of ... linker error
提问by mazix
I defined a special file: config.h
我定义了一个特殊文件: config.h
My project also has files:
我的项目也有文件:
t.c, t.h
pp.c, pp.h
b.c b.h
l.cpp
and #includes:
和#includes:
in t.c:
在 tc 中:
#include "t.h"
#include "b.h"
#include "pp.h"
#include "config.h"
in b.c:
在公元前:
#include "b.h"
#include "pp.h"
in pp.c:
在pp.c中:
#include "pp.h"
#include "config.h"
in l.cpp:
在 l.cpp 中:
#include "pp.h"
#include "t.h"
#include "config.h"
there are no include directives in my *.hfiles, only in *.cfiles. I defined this in config.h:
我的*.h文件中没有包含指令,只有在*.c文件中。我在 config.h 中定义了这个:
const char *names[i] =
{
"brian", "stefan", "steve"
};
and need that array in l.cpp, t.c, pp.c but Im getting this error:
并需要 l.cpp、tc、pp.c 中的数组,但我收到此错误:
pp.o:(.data+0x0): multiple definition of `names'
l.o:(.data+0x0): first defined here
t.o:(.data+0x0): multiple definition of `names'
l.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [link] Error 1
I have include guards in every *.hfile I use in my project. Any help solving this?
我*.h在我的项目中使用的每个文件中都包含了守卫。任何帮助解决这个问题?
回答by Yu Hao
Don't define variables in headers. Put declarations in header and definitions in one of the .c files.
不要在标题中定义变量。将声明放在头文件中,并将定义放在 .c 文件之一中。
In config.h
在 config.h
extern const char *names[];
In some .c file:
在一些 .c 文件中:
const char *names[] =
{
"brian", "stefan", "steve"
};
If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.
如果你把一个全局变量的定义放在一个头文件中,那么这个定义将进入每个包含这个头的 .c 文件,你会得到多个定义错误,因为一个变量可能被多次声明但只能被定义一次.
回答by JonathanWhittenberg
Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)
公共函数的声明在头文件中,是的,但定义在头文件中也绝对有效!如果您在实用程序的头文件中定义不想在每个 c 文件中再次定义的内容,您可以将定义声明为静态(整个程序只允许 1 个副本)。IE 定义了一个枚举和一个将枚举转换为字符串的静态函数。然后,您不必为包含标头的每个 .c 文件重写枚举到字符串转换器。:)

