C++ 链接到单独的.cpp文件说"multiple definitions"

C++ Linking to separate .cpp file says "multiple definitions"

本文关键字:multiple definitions 文件 cpp 链接 单独 C++      更新时间:2023-10-16

我对C++很陌生,可以使用一些帮助。我正在尝试将文件my_help_fxns.cpp链接到我的 main.cpp 文件,以便我可以在 main.cpp 中使用这些函数,但是当我尝试链接时,my_help_fxns中的每个函数都收到以下错误:

C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:UsersGeoffAppDataLocalTempccaPL79E.o:data_vars_class.cpp:(.text+0x0): multiple definition of `my_help_fxns::print_vector_items_int_type(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::vector<int, std::allocator<int> >)'; C:UsersGeoffAppDataLocalTempcc0mRP1w.o:main.cpp:(.text+0x0): first defined here

所以它说我正在定义两次,但我不知道如何解决这个问题。我有一个名为 data_vars_class 的类,我在data_vars_class.cpp的顶部包含my_help_fxns,并在该类的方法中成功使用辅助程序 fxns。类的实例在 main.cpp 的顶部创建。但是,如果我尝试在 main.cpp 中使用 main(( 中的辅助函数,而没有在 main.cpp 的顶部声明"my_help_fxns.cpp",它说找不到函数,如果我确实在 main.cpp 的顶部声明它,我得到重复错误它被声明了两次。我该如何解决这个问题,谢谢!

这是我的项目结构

主要.cpp ==>

#include "data_vars_class.hpp"
#include <iostream>
#include <chrono>
#include "my_help_fxns.cpp"   <--- including here gives duplication error, but if i dont, its functions not found error
DataVars dataVars;
int main () {
my_help_fxns::pause_program();
return 0; 
}

data_vars_class.hpp ==>

#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
class DataVars
{
private:
...
public:
...
}

data_vars_class.cpp==>

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <array>
#include "data_vars_class.hpp"
#include "my_help_fxns.cpp"
...i can use my_help_fxns here with no problem, as an instance of this class is created before main() in main.cpp

my_help_fxns.cpp ==>

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
namespace my_help_fxns
{
void pause_program() {
std::string dummy;
std::cout << "Enter to continue..." << std::endl;
std::getline(std::cin, dummy);            
}
}

这是 Geany 中文件的构建命令:

g++ main.cpp data_vars_class.cpp -o a.out

感谢您的帮助!

不要将my_help_fxns.cpp包含在其他 CPP 文件中,因为这将在所有 CPP 文件中有效地定义这些函数。这违反了一个定义规则。

相反

  • 创建一个声明(但不定义(这些函数头文件
  • 在所有 CPP 文件中包含该头文件
  • my_help_fxns.cpp添加到编译命令行

按照如下所述对文件进行更改:

主.cpp

#include "data_vars_class.hpp"
#include <iostream>
#include <chrono>
#include "my_help_fxns.hpp" // change file extension from cpp -> hpp
DataVars dataVars;
int main () {
my_help_fxns::pause_program();
return 0; 
}

data_vars_class

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <array>
#include "data_vars_class.hpp"
// #include "my_help_fxns.cpp" --> Not required here

然后你可以简单地运行:

g++ -o a.out main.cpp; ./a.out

在这里给出:

Enter to continue...
sdfsdfsdfsd    // --- INPUT