c++ - 当头文件(a.hpp)包含在头文件(b.hpp)对应的源文件(b.cpp)和main.cpp中时,C ++修复多重定义错误
问题描述
我在 Ubuntu 16.04LTS 中有以下四个文件a.hpp、b.hpp、b.cpp和main.cpp,它们模仿了我的原始文件。
一个.hpp
#ifndef A_H
#define A_H
#include <iostream>
namespace Utility{
typedef struct _structure{
int v;
int w;
}aStructure;
void foo(){
std::cout << "foo" << std::endl;
}
void goo(){
foo();
}
}
#endif
b.hpp
#ifndef B_H
#define B_H
#include <iostream>
#include "a.hpp"
class bCls{
private:
int x;
public:
void moo(Utility::aStructure s);
};
#endif
b.cpp
#include <iostream>
#include "a.hpp"
#include "b.hpp"
void bCls::moo(Utility::aStructure s){
std::cout << "moo" << std::endl;
}
主文件
#include <iostream>
#include "a.hpp"
#include "b.hpp"
int main(){
Utility::aStructure s;
bCls u;
u.moo(s);
return 0;
}
当我尝试使用g++ -std=c++11 b.cpp main.cpp进行编译时,会抛出以下错误消息:
/tmp/ccwvPrRr.o: In function `Utility::foo()':
main.cpp:(.text+0x0): multiple definition of `Utility::foo()'
/tmp/ccCVJOoH.o:b.cpp:(.text+0x0): first defined here
/tmp/ccwvPrRr.o: In function `Utility::goo()':
main.cpp:(.text+0x23): multiple definition of `Utility::goo()'
/tmp/ccCVJOoH.o:b.cpp:(.text+0x23): first defined here
collect2: error: ld returned 1 exit status
我的搜索导致包含标题时为什么会出现多个定义错误?. 但我的代码中的一个区别是b.hpp、b.cpp和main.cpp都需要a.hpp。
我很想知道我做错了什么以及在这种情况下编写代码的最佳方法以及相应的陷阱。
解决方案
推荐阅读
- python - Paho MQTT 客户端断开连接,重新连接后不再有消息传入
- ios - 孤立的工件 iMessage 扩展 - iOS 错误
- python - Django在退出管理页面时运行功能
- java - 无法在 servlet 中创建没有 web.xml 的第一个 api
- mysql - MYSQL CTE 递归更新
- vue.js - ELEMENT UI - 如何增加 ICON 的大小?
- asp.net - 如何使用 VB.NET 从 WebAPI 获取 JSON 数据?
- perl - 从 perl 数组中删除重复的哈希
- python - 掷骰子游戏的一些建议
- python - 在 GNU Radio 中使用 USRP 进行频谱感知