我正在尝试使用mac上的cmake编译测试类.当我运行cmake和make命令时,我最终得到了这个错误:
duplicate symbol _main in:
CMakeFiles/Carm.dir/CMakeFiles/3.7.0/CompilerIdCXX/CMakeCXXCompilerId.cpp.o
CMakeFiles/Carm.dir/test.cpp.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [Carm] Error 1
make[1]: *** [CMakeFiles/Carm.dir/all] Error 2
make: *** [all] Error 2
Run Code Online (Sandbox Code Playgroud)
告诉我在main中有一个重复的符号.当我单独使用g ++时,这段代码可以完美编译.
car.h
#ifndef CAR_H
#define CAR_H
#include <string>
using namespace std;
namespace test {
class Car {
private:
string model;
int hp;
int speed;
public:
Car(string n_model, int n_hp);
string getModel();
int getHp();
int getSpeed();
};
}
#endif
Run Code Online (Sandbox Code Playgroud)
car.cpp
#include "car.h"
using namespace test;
Car::Car(string n_model, int n_hp) {
model = n_model;
hp = n_hp;
speed = 0;
}
string Car::getModel() {
return model;
}
int Car::getHp() {
return hp;
}
int Car::getSpeed() {
return speed;
}
Run Code Online (Sandbox Code Playgroud)
TEST.CPP
#include "car.h"
#include <cstdio>
using namespace std;
using namespace test;
int main() {
Car car1("BMW", 400);
Car car2("Hellcat", 707);
printf("hp-%d speed-%d\n", car1.getHp(), car1.getSpeed());
printf("hp-%d speed-%d\n", car2.getHp(), car2.getSpeed());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的CMakeLists.txt文件
cmake_minimum_required(VERSION 2.8)
project(Carm)
file(GLOB_RECURSE Carm_SOURCES "*.cpp")
file(GLOB_RECURSE Carm_HEADERS "*.h")
set(Carm_INCLUDE_DIRS "")
foreach(_headerFile ${Carm_HEADERS})
get_filename_component(_dir ${_headerFile} PATH)
list(APPEND Carm_INCLUDE_DIRS ${_dir})
endforeach()
list(REMOVE_DUPLICATES Carm_INCLUDE_DIRS)
include_directories(${Carm_INCLUDE_DIRS})
add_executable(Carm ${Carm_SOURCES})
Run Code Online (Sandbox Code Playgroud)
在你的可执行文件,你有两个主要功能(打印出来Carm_SOURCES的MESSAGE(${Carm_SOURCES})).一个是test.cpp,一个在CMakeCXXCompilerId.cpp(这是CMake的生成来测试,如果你的CXX编译器正常工作的文件).该GLOB_RECURSE认定,并增加了这两个文件,以Carm_SOURCES
建议不要用于GLOB收集源文件列表.从文件(GLOB文档:
我们不建议使用GLOB从源树中收集源文件列表.如果在添加或删除源时没有更改CMakeLists.txt文件,则生成的构建系统无法知道何时请求CMake重新生成.
列出项目文件的推荐方法是手动添加它们CMakeLists.txt.