为什么会出现“多个定义"错误?我如何解决它? [英] Why am I getting a 'multiple definition' error? how do i fix it?

查看:47
本文介绍了为什么会出现“多个定义"错误?我如何解决它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

终端发出的命令:

g ++ main.cpp test.cpp

g++ main.cpp test.cpp

错误消息:

/tmp/ccvgRjlI.o:在函数"test2()"中:
test.cpp :(.text + 0x0):多个test2()的定义
/tmp/ccGvwiUE.o:main.cpp:(.text+0x0):首先在此处定义
collect2:错误:ld返回1退出状态main.cpp

/tmp/ccvgRjlI.o: In function `test2()':
test.cpp:(.text+0x0): multiple definition of `test2()'
/tmp/ccGvwiUE.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status main.cpp

源代码:

#include "test.hpp"
int main(int argc, char *argv[])
{
    test2();
    return 0;
}

test.hpp

#ifndef _TEST_HPP_
#define _TEST_HPP_

#include <iostream>

void test();
void test2() { std::cerr << "test2" << std::endl; }

#endif

test.cpp

#include "test.hpp"

using std::cerr;
using std::endl;

void test() { cerr << "test" << endl; }

下面的命令可以很好地编译:

btw the following compiles fine:

g ++ main.cpp

g++ main.cpp

推荐答案

头文件 test.hpp 包含在两个编译单元中.第一个是编译单元 main.cpp ,第二个是编译单元 test.cpp .

The header test.hpp is included in two compilation units. The first one is the compilation unit main.cpp and the second one is the compilation unit test.cpp.

默认情况下,功能具有外部链接.这意味着具有相同名称和签名的函数在不同的编译单元中表示相同的函数.它们应定义一次.但是,在您的程序中,在两个编译单元中找到了函数 test2 的定义,并且链接程序不知道要使用的函数的定义.

Functions by default have external linkage. This means that functions with the same name and signature denote the same function in different compilation units. They shall be defined once. However in your program the definition of the function test2 is found in two compilation units and the linker does not know what definition of the function to use.

您可以将该函数声明为内联函数.例如

You could declare the function as an inline function. For example

inline void test2() { std::cerr << "test2" << std::endl; }

在这种情况下,它可以在每个编译单元中定义.

In this case it may be defined in each compilation unit.

或者您也可以仅将使用函数 test 进行的函数声明放在标头中,并在 test.cpp 中进行定义.

Or you can place in the header only the function declaration as you made with the function test and define it for example in test.cpp.

另一种方法是将函数声明为具有内部链接.为此,您可以在标题中使用关键字static

Another way is to declare the function as having internal linkage. To do this you can define the function in the header either with the keyword static

static void test2() { std::cerr << "test2" << std::endl; }

或将其放置在未命名的名称空间中

or place it in unnamed name space

namespace
{
    void test2() { std::cerr << "test2" << std::endl; }
}

在这种情况下,每个编译单元将具有其自己的函数 test2 .

In this case each compilation unit will have its own function test2.

这篇关于为什么会出现“多个定义"错误?我如何解决它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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