在CLion中使用CMake使用参数编译C ++会抛出错误,而在终端中编译则不会

时间:2019-01-22 19:59:31

标签: c++ cmake parameter-passing sfml clion

我有一个使用SFML库的简单代码,需要使用

进行编译

-lsfml-graphics -lsfml-system -lsfml-window参数。

当我仅使用cmd时,效果很好

  g++ gejm.cpp -o gejm -lsfml-graphics -lsfml-system -lsfml-window

  .\gejm.exe

但是,当我使用CLion运行它时,会出现错误,好像没有传递我的参数一样。但是我知道我的参数已经通过,因为如果我拼错了其中的任何一个参数,甚至在我的代码被编译之前都会引发错误。

我的CMakeLists.txt看起来像这样

set(GCC_COVERAGE_COMPILE_FLAGS "-lsfml-graphics -lsfml-system -lsfml-window")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}" )

add_executable(gejm gejm.cpp)

那是什么问题?

...这是错误

CMakeFiles\gejm.dir/objects.a(gejm.obj): In function `main':
D:/Projects/CPP/GUI/gejm.cpp:8: undefined reference to `_imp___ZN2sf6StringC1EPKcRKSt6locale'
D:/Projects/CPP/GUI/gejm.cpp:8: undefined reference to `_imp___ZN2sf9VideoModeC1Ejjj'
D:/Projects/CPP/GUI/gejm.cpp:8: undefined reference to `_imp___ZN2sf12RenderWindowC1ENS_9VideoModeERKNS_6StringEjRKNS_15ContextSettingsE'
D:/Projects/CPP/GUI/gejm.cpp:9: undefined reference to `_imp___ZNK2sf10WindowBase6isOpenEv'
D:/Projects/CPP/GUI/gejm.cpp:11: undefined reference to `_imp___ZN2sf10WindowBase9pollEventERNS_5EventE'
D:/Projects/CPP/GUI/gejm.cpp:13: undefined reference to `_imp___ZN2sf6Window5closeEv'
D:/Projects/CPP/GUI/gejm.cpp:17: undefined reference to `_imp___ZN2sf5ColorC1Ehhhh'
D:/Projects/CPP/GUI/gejm.cpp:17: undefined reference to `_imp___ZN2sf12RenderTarget5clearERKNS_5ColorE'
D:/Projects/CPP/GUI/gejm.cpp:18: undefined reference to `_imp___ZN2sf6Window7displayEv'
D:/Projects/CPP/GUI/gejm.cpp:8: undefined reference to `_imp___ZN2sf12RenderWindowD1Ev'
D:/Projects/CPP/GUI/gejm.cpp:8: undefined reference to `_imp___ZN2sf12RenderWindowD1Ev'
collect2.exe: error: ld returned 1 exit status
CMakeFiles\gejm.dir\build.make:84: recipe for target 'gejm.exe' failed
CMakeFiles\Makefile2:71: recipe for target 'CMakeFiles/gejm.dir/all' failed
mingw32-make.exe[3]: *** [gejm.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/gejm.dir/all] Error 2
CMakeFiles\Makefile2:83: recipe for target 'CMakeFiles/gejm.dir/rule' failed
mingw32-make.exe[1]: *** [CMakeFiles/gejm.dir/rule] Error 2
mingw32-make.exe: *** [gejm] Error 2
Makefile:117: recipe for target 'gejm' failed

1 个答案:

答案 0 :(得分:0)

这不是添加库的方法:

set(GCC_COVERAGE_COMPILE_FLAGS "-lsfml-graphics -lsfml-system -lsfml-window")

将这些库添加到库列表中:

target_link_libraries(gejm PUBLIC sfml-graphics sfml-system sfml-window)

之所以不起作用,是因为链接阶段不是编译阶段,您仅覆盖编译标志,而不覆盖链接标志。无论如何,这不是正确的方法。使用CMake提供的功能,请勿入侵。