Linking GSL in Cmakelists.txt in CLion

做~自己de王妃 提交于 2019-12-02 05:45:12

问题


I have a code with multiple files, that uses the GSL Library. When I compile the code through the terminal with the command

g++ main.cpp -lm -lgsl -lgslcblas -o Exec

This compiles and gives the correct output and no errors. However, when I try and build the code in CLion I get the error

undefined reference to `gsl_rng_uniform'

I have linked the various .cpp files in my code through the CMakeLists.txt, but I think, I have to something similar to the flags to link to GSL. My CMakeLists.txt file is as follows currently (only the .cpp files are included in the source files, not the .h files):

cmake_minimum_required(VERSION 3.7)
project(Unitsv1)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp
                 transition.cpp
                 random.cpp)
add_executable(Unitsv1 ${SOURCE_FILES})

I'm very new to C++, and can't seem to find any answers online. Thanks


回答1:


You haven't linked in the GSL libraries, so the linker won't find any of the symbols it provides. Something like this should get you most of the way there:

cmake_minimum_required(VERSION 3.7)
project(Unitsv1)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED YES)   # See below (1)

set(SOURCE_FILES main.cpp
                 transition.cpp
                 random.cpp)
add_executable(Unitsv1 ${SOURCE_FILES})

find_package(GSL REQUIRED)    # See below (2)
target_link_libraries(Unitsv1 GSL::gsl GSL::gslcblas)

If your code uses C++11, then you need the line at (1) to ensure you actually get C++11 support. Without CMAKE_CXX_STANDARD_REQUIRED YES, the CMAKE_CXX_STANDARD variable acts only as "Use it if it is available, or fall back to the closest standard the compiler can provide". You can find a detailed write-up here if you're curious.

The more important part for your question is at (2). The find_package() command looks for the GSL libraries, etc. and makes them available as import targets GSL::gsl and GSL::gslcblas. You then use target_link_libraries() to link your executable to them as shown. The CMake documentation explains how the find_package() side of things works in plenty of detail:

  • Start here: find_package()
  • Specifics for GSL: FindGSL module
  • Linking: target_link_libraries()


来源:https://stackoverflow.com/questions/44821615/linking-gsl-in-cmakelists-txt-in-clion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!