How to link ROOT libraries using separate CMakeLists.txt

Hi,
When I use CMake to compile a C++ program that using ROOT library.I’m in a trouble.
The directory structure of this program like this :
├── build
├── CMakeLists.txt
├── include
│ └── Recoil_Energy_Spectrum.hh
└── src
├── CMakeLists.txt
└── Recoil_Energy_Spectrum.cc
The contents of CMakeLists.txt in PROJECT_SOURCE_DIR:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(Recoil_Energy_Spectrum)
set(CMAKE_CXX_FLAGS "-std=c++11")
find_package(ROOT REQUIRED)
include_directories(${PROJECT_SOURCE_DIR}/include ${ROOT_INCLUDE_DIRS})
link_directories($ENV{ROOTSYS}/lib)
add_subdirectory(src)

And the contents of CMakeLists.txt in /src :

add_executable(Recoil_Energy_Spectrum Recoil_Energy_Spectrum.cc)
target_link_directories(Recoil_Energy_Spectrum PUBLIC ${ROOT_LIBRARIES})

When I compile this program,the compiler said it could’t link to ROOT libraries.How to solve this problem?
Thanks.
ROOT Version: 6.20/02
Platform: Linux
Compiler: GNU 8.3.0


Welcome to the ROOT Forum!
Try with

link_directories(${ROOT_LIBRARY_DIR})

Thanks for reply.But the compiler still gives errors like this:Recoil_Energy_Spectrum.cc:(.text+0x2a4): undefined reference to `TFile::Open(char const*, char const*, char const*, int, int)’

Why do you have two CMakeLists.txt and not having all in the top level one?

Hi @shadow1OVO ,

and welcome to the ROOT forum!

I don’t think link_directories is enough, that just adds the -L flag to the compilation (i.e. where to look for libraries) but you still need to mention which libraries your target depend on. You do that with target_link_libraries, see the example at Integrating ROOT into CMake projects - ROOT or a full working project such as GitHub - eguiraud/root-readspeed: A tool to measure what throughput can be expected from ROOT for a given application. .

Cheers,
Enrico

I have solved this problem.Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.