关于C#:…链接器错误的多个定义

Multiple definition of … linker error

我定义了一个特殊文件:config.h

我的项目还有文件:

1
2
3
4
t.c, t.h
pp.c, pp.h
b.c b.h
l.cpp

和#includes:

在t.c中:

1
2
3
4
    #include"t.h"
    #include"b.h"
    #include"pp.h"
    #include"config.h"

在公元前:

1
2
    #include"b.h"
    #include"pp.h"

在pp.c中:

1
2
    #include"pp.h"
    #include"config.h"

在l.cpp中:

1
2
3
    #include"pp.h"
    #include"t.h"
    #include"config.h"

我的*.h文件中没有include伪指令,仅在*.c文件中。 我在config.h中定义了这个:

1
2
3
4
const char *names[i] =
        {
           "brian","stefan","steve"
        };

并需要在l.cpp,t.c,pp.c中使用该数组,但我收到此错误:

1
2
3
4
5
6
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

我在项目中使用的每个*.h文件中都包含防护措施。 对解决这个有帮助吗?


不要在标题中定义变量。 将声明放在标头中,并将定义放在.c文件之一中。

在config.h中

1
extern const char *names[];

在某些.c文件中:

1
2
3
4
const char *names[] =
    {
       "brian","stefan","steve"
    };

如果将全局变量的定义放在头文件中,则此定义将进入包含该头文件的每个.c文件,并且会出现多个定义错误,因为变量可能被声明多次,但只能定义一次 。


公共函数的声明放在头文件中,是的,但是定义在头文件中也绝对有效! 如果您要在不需要在每个c文件中再次定义的实用程序函数的标头中定义内容,则可以将定义声明为静态(整个程序仅允许1个副本)。 即 定义枚举和静态函数以将枚举转换为字符串。 这样,您就不必为包含头文件的每个.c文件将枚举重写为字符串转换器。 :)