Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking GSL in CMakeLists.txt

Tags:

c++

cmake

gsl

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

like image 495
Kahealani Avatar asked Dec 10 '22 11:12

Kahealani


1 Answers

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()
like image 89
Craig Scott Avatar answered Dec 14 '22 05:12

Craig Scott