Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

c++ - Linking GSL in CMakeLists.txt

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...