c - 多重定义 ... 链接器错误

标签 c linker linker-errors

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

我的项目也有文件:

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

和#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 文件中没有include 指令,只有在*.c 文件中。我在 config.h 中定义了这个:

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

并且在 l.cpp、t.c、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

我在项目中使用的每个 *.h 文件中都包含了守卫。有帮助解决这个问题吗?

最佳答案

不要在标题中定义变量。将声明放在 header 中,将定义放在其中一个 .c 文件中。

在config.h中

extern const char *names[];

在一些 .c 文件中:

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

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

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

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

这样变量 names 将在整个程序中只定义一次,并且可以多次访问。

关于c - 多重定义 ... 链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764661/

相关文章:

c++ - 如何知道portaudio样本测试正弦波码的频率

c++ - 在我从旧版 DirectX SDK 更改为 Windows SDK(Visual Studio 2015)后,链接器一直在提示)

C++ 链接器错误,未解析的外部

c++ - 我对 SDL 的简单介绍程序没有构建。为什么我会收到这些链接器错误?

c++ - 使用 Microsoft Visual C++ 6.0 解决 __imp__open 和其他类似命名函数的链接错误

c++ - 2的平方根,点后需要x位数字

c++ - 如何将 3 个嵌套循环的函数变成一个递归函数?

opencv - 将 OpenCV 链接到 Webots(Ubuntu) 时出现问题

c - Gtk VB OLE 对象

使用 pthread 编译/链接错误