我有一个主要的方法,
main.cpp:
#include "MyStruct.h"
MyStruct.h:
#ifndef MYPROJ_MYSTRUCT_H
#define MYPROJ_MYSTRUCT_H
#include <vector>
#include <unordered_map>
bool function1(std::vector<std::string> label){
// actual implementation
}
bool function2(...){ ... }
struct MyStruct{ ... }
#endif
这编译。但是,当我添加cpp
文件以包含函数定义时,
main.cpp:
#include "MyStruct.h"
MyStruct.h:
#ifndef MYPROJ_MYSTRUCT_H
#define MYPROJ_MYSTRUCT_H
#include <vector>
bool function1(...){ ... }
bool function2(...){ ... }
struct MyStruct{ ... }
#endif
MyStruct.cpp:
#include "MyStruct.h"
// and that's it
仅仅通过包含头文件,我就会收到链接器错误,就像我多次导入头文件一样;
这是 CMakeLists:
cmake_minimum_required(VERSION 3.8)
set(CMAKE_CXX_STANDARD 17)
set(SOURCE_FILES main.cpp MyStruct.cpp)
add_executable(my_proj ${SOURCE_FILES})
错误包括所有重复的符号错误。我不知道如何让它工作,因为这是我一直使用 make 和 g++ 做的事情而没有遇到问题;当我在 Cygwin/Windows 上使用带有 g++ 的 CMake 时,我似乎也没有这个问题(这是在 MacOSX 上)。
接下来,当我将所有函数转换到 .cpp 文件时,并且只有声明出现在标题中时,我消除了大部分重复符号,除了:
duplicate symbol __Z8get_uvidv in:
CMakeFiles/main.cpp.o
CMakeFiles/MyStruct.cpp.o
duplicate symbol _uvid in:
CMakeFiles/main.cpp.o
CMakeFiles/MyStruct.cpp.o
ld: 2 duplicate symbols for architecture x86_64
更新来源
// header: MyStruct.h
#ifndef MYPROJ_MYSTRUCT_H
#define MYPROJ_MYSTRUCT_H
#include <unordered_map>
#include <vector>
#include "AnotherStruct.h"
bool add_item(std::pair<std::string,float> & item);
void insert_item(std::vector<AnotherStruct> & A, std::pair<std::string,float> element);
...
struct MyStruct {
std::unordered_map<std::string,int> labels;
std::vector<AnotherStruct> data;
MyStruct(std::vector<char *> inputs);
void GetData();
void SortData(bool (*compare)(AnotherStruct &,AnotherStruct &);
//...
}
#endif
和.cpp
:
#include "MyStruct.h"
// implement everything declared in .h
bool add_item(...){
...
}
bool insert_item(...){
...
}
MyStruct::MyStruct(...){
...
}
void MyStruct::GetData(...){
...
}
void MyStruct::SortData(...){
...
}
和主要的:
#include "MyStruct.h"
错误:
duplicate symbol __Z8get_uvidv in:
main.cpp.o
MyStruct.cpp.o
duplicate symbol _uvid in:
main.cpp.o
MyStruct.cpp.o
我不知道__Z8get_uvidv
可能是什么,也不知道_uvid
,所以我认为std imports
, 或引擎盖下的编译器发生了一些事情。
请记住,当我将其复制到 main 方法或将所有定义保留在头文件中时,一切都会编译,我很难过。
您已包含MyStruct.h
在main.cpp
和 中MyStruct.cpp
。
包括基本没有复制粘贴,让你有2个翻译单元(main.cpp
和MyStruct.cpp
),这两个包含定义function1
和function2
(因为你同时包括在头文件)。
解决方案:
仅在头文件中声明函数并仅在一个翻译单元中定义它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句