终端给出的命令:
g++ main.cpp 测试.cpp
错误信息:
/tmp/ccvgRjlI.o:在函数“test2()”中:
test.cpp:(.text+0x0): 多个
`test2()' 的定义
/tmp/ccGvwiUE.o:main.cpp:(.text+0x0):首先在这里定义
collect2:错误:ld 返回 1 退出状态
主程序
源代码:
#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; }
顺便说一句,以下编译良好:
g++ main.cpp
标题test.hpp
包含在两个编译单元中。第一个是编译单元main.cpp
第二个是编译单元test.cpp
.
默认情况下,函数具有外部链接。这意味着具有相同名称和签名的函数在不同编译单元中表示相同的函数。它们应被定义一次。然而在你的程序中函数的定义test2
在两个编译单元中找到并且链接器不知道要使用该函数的什么定义。
您可以将该函数声明为内联函数。例如
inline void test2() { std::cerr << "test2" << std::endl; }
在这种情况下,它可以在每个编译单元中定义。
或者,您可以仅将使用函数所做的函数声明放入标头中test
并定义它例如test.cpp
.
另一种方法是将函数声明为具有内部链接。为此,您可以使用关键字 static 在标头中定义函数
static void test2() { std::cerr << "test2" << std::endl; }
或将其放置在未命名的名称空间中
namespace
{
void test2() { std::cerr << "test2" << std::endl; }
}
在这种情况下,每个编译单元都会有自己的功能test2
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)