【发布时间】:2017-05-26 15:35:02
【问题描述】:
终端给出的命令:
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
源代码:
#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
【问题讨论】:
-
在 test2 之前添加
inline关键字以绕过单一定义规则。 -
与您的问题无关,但像
_TEST_HPP_这样的名称在 C++ 中是保留的。去掉开头的下划线。 -
@latedeveloper TEST_HPP 会好吗?
-
@lost 是的,那很好。
标签: c++ g++ linker-errors