問題描述
common.h定義所有的類型別名和結構體聲明,被mass_diffusion.h和 heat_conduction.h所引用,mass_diffusion.h和heat_conduction.h被man.cpp所引用,然後編譯成功,連結的時候報錯LINK2005
。我已經使用了#ifndef ... #define ... #endif
這種防禦性語法;每個檔案暴露在外面的只有一個init函數,檔案內部雖然都有重名函數,但是他們沒有對外暴露為什麼還會報錯?
錯誤訊息
visual studio 2017 編譯C++ 錯報:LNK2005 mass_diffusion.obj中的"void __cdecl compute(class std::vector<struct user ,structuser # class std::allocator<struct user > > ,class std::vector<struct item ,class std::allocator<struct item > > ) "已經在heat_conduction.obj 中定義。
#相關程式碼
//common.h
#ifndef _COMMON_H
#define _COMMON_H
...
struct user;
struct item;
struct relation;
...
typedef unsigned int _container_number_;
typedef unsigned int _value_number_;
...
typedef std::vector<user*> user_container;##typedefd:: vector<item*> item_container;
#endif // !_COMMON_H
...
//mass_diffusion.h##include "common.h"
extern void init_md(user_container
, item_container);void compute(user_container
_ulist, item_container _ilist);...
//mass_diffusion. cpp#include "mass_diffusion.h"
void init_md(user_container
_ulist, item_container _ilist){...};void compute(user_container
_ilist){...};void compute(user_container _ulist,
_ulist,
item_container _ilist) {...};...
//heat_conduction.h#include "common.h"
extern void init_hc(user_container _ulist, item_container _ilist);
void compute(user_container
_ulist, item_container _ilist);...
//heat_conduction.cppinclude "heat_conduction.h"
void init_hc(user_container _ulist, item_container _ilist){...};
void compute(user_container
_ulist){...};void compute(user_container _ulist, it#container,# # _ilist) {...};
...
本來就會報錯,你各個模組都連結到同一個檔案裡,連結器一看那麼多符號都一個名字自然就gg了,.h裡面暴露什麼連結器不會管的,解決方法是各個模組獨立編譯成so或dll,然後再調用,或用命名空間