小编los*_*ost的帖子

为什么我会收到“多重定义”错误?我如何解决它?

终端给出的命令:

g++ main.cpp 测试.cpp

错误信息:

/tmp/ccvgRjlI.o: 在函数 `test2()' 中:
test.cpp:(.text+0x0): `test2()' 的多重定义
/tmp/ccGvwiUE.o:main.cpp:(.text+0x0 ): 首先在这里定义
collect2: error: ld returned 1 exit status main.cpp

源代码:

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

测试.hpp

#ifndef _TEST_HPP_
#define _TEST_HPP_

#include <iostream>

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

#endif
Run Code Online (Sandbox Code Playgroud)

测试.cpp

#include "test.hpp"

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

void test() { cerr << "test" << endl; }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,以下编译良好:

g++ main.cpp

c++ g++ linker-errors

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

g++ ×1

linker-errors ×1