问题描述
我正在构建一个程序只是为了提高我的 OOP 技能。这是我的项目结构:
Project
-.vscode
-build
-includes
- ContactInfo.h
- Customer.h
- Owner.h
- PersonalInfo.h
- User.h
-src
- ContactInfo.cpp
- Customer.cpp
- Owner.cpp
- PersonalInfo.cpp
- User.cpp
- wrapper.h
- wrapper.cpp
- main.cpp
- CMakeLists.txt
问题是当我在 cmd 中的构建文件路径中键入命令 make
时,出现以下错误:
duplicate symbol '_key' in:
CMakeFiles/make_test_project.dir/src/main.cpp.o
CMakeFiles/make_test_project.dir/src/wrapper.cpp.o
duplicate symbol '_customers' in:
CMakeFiles/make_test_project.dir/src/main.cpp.o
CMakeFiles/make_test_project.dir/src/wrapper.cpp.o
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command Failed with exit code 1 (use -v to see invocation)
make[2]: *** [make_test_project] Error 1
make[1]: *** [CMakeFiles/make_test_project.dir/all] Error 2
make: *** [all] Error 2
我能猜到这里发生了什么,我基本上在 wrapper.h
和 main.cpp
文件中都包含了 wrapper.cpp
文件,但我不知道如何修复它。我也想以这种方式保持我的项目结构。那么有没有办法修复这个错误?
这是我的 wrapper.h
文件:
#ifndef WRAPPER_H
#define WRAPPER_H
#include "../includes/Customer.h"
#include <vector>
#include <iostream>
char key;
void printUI();
void RunApplication();
PersonalInfo CreatePersonalInfo(std::string &,std::string &,int & );
ContactInfo CreateContactInfo(std::string &,int&);
void displayAllCustomers();
void AddCustomerToList(Customer &);
Customer CreateCustomer(PersonalInfo &,ContactInfo &);
std::vector<Customer> customers;
#endif
这是我的 main.cpp
文件:
#include "wrapper.h"
int main()
{
RunApplication();
}
下面是我的 CMakeLists.txt
文件:
cmake_minimum_required(VERSION 3.13)
project(cmake_test_project)
set(CMAKE_CXX_STANDARD 17)
add_executable(make_test_project src/main.cpp src/wrapper.cpp src/ContactInfo.cpp src/PersonalInfo.cpp src/Customer.cpp src/User.cpp)
注意:我不会分享 wrapper.cpp
文件,因为它是一个由近 120 行组成的文件,但我可以告诉你我还在 wrapper.h
文件中包含了 wrapper.cpp
文件.
请随时询问更多信息,谢谢。
解决方法
在你的 wrapper.h 中
extern char key;
void printUI();
void RunApplication();
PersonalInfo CreatePersonalInfo(std::string &,std::string &,int & );
ContactInfo CreateContactInfo(std::string &,int&);
void DisplayAllCustomers();
void AddCustomerToList(Customer &);
Customer CreateCustomer(PersonalInfo &,ContactInfo &);
extern std::vector<Customer> customers;
并在一个且只有一个 .cpp 文件中声明。
如果你有 C++17 你可以用 inline
交换 extern 就完成了。