... 链接器错误的多重定义 [英] Multiple definition of ... linker error

查看:26
本文介绍了... 链接器错误的多重定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I defined a special file: config.h

我的项目也有文件:

t.c, t.h
pp.c, pp.h
b.c b.h
l.cpp

和#includes:

and #includes:

在 t.c 中:

    #include "t.h"
    #include "b.h"
    #include "pp.h"
    #include "config.h"

在公元前:

    #include "b.h"
    #include "pp.h"

在 pp.c 中:

    #include "pp.h"
    #include "config.h"

在 l.cpp 中:

    #include "pp.h"
    #include "t.h"
    #include "config.h"

在我的 *.h 文件中没有包含指令,只有在 *.c 文件中.我在 config.h 中定义了这个:

there are no include directives in my *.h files, only in *.c files. I defined this in config.h:

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

并且需要 l.cpp、t.c、pp.c 中的该数组,但我收到此错误:

and need that array in l.cpp, t.c, pp.c but Im getting this error:

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 文件中都包含了保护.有帮助解决这个问题吗?

I have include guards in every *.h file I use in my project. Any help solving this?

推荐答案

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

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

在 config.h 中

In config.h

extern const char *names[];

在一些 .c 文件中:

In some .c file:

const char *names[] = { 
  "brian", "stefan", "steve" };

如果你把一个全局变量的定义放在一个头文件中,那么这个定义将转到每个包含这个头文件的 .c 文件,你会得到多重定义错误,因为一个变量可能被声明多次,但可以只定义一次.

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.

此外,如果您必须在头文件中定义变量,您还可以做一件事,您可以使用 static 关键字.

Also, one more thing you can do if you have to define your variables inside of a header file you can use the static keyword.

static const char *names[] = {
  "brian", "stefan", "steve" };

这样变量names在你的整个程序中只会被定义一次,并且可以被多次访问.

This way variable names will be defined only once in your entire program and can be accessed multiple number of times.

这篇关于... 链接器错误的多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆