NikaTsanka
NikaTsanka

Reputation: 17

cmake link xlib directories c++

I'm trying to compile a c++ program that uses xlib with cmake. However, I'm having a problem including and linking xlib libraries in cmake file.

This is the error that I'm getting.

 main.cpp:378: undefined reference to `XClearWindow'
 collect2: error: ld returned 1 exit status
 CMakeFiles/project1.dir/build.make:94: recipe for target 'project1' failed
 make[2]: *** [project1] Error 1
 CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/project1.dir/all' failed
 make[1]: *** [CMakeFiles/project1.dir/all] Error 2
 Makefile:83: recipe for target 'all' failed
 make: *** [all] Error 2

And when I use just the command line to compile, it works just fine.

I use this command (g++ main.cpp -L/usr/X11R6/lib -lX11)

and this is my cmake file.

cmake_minimum_required(VERSION 3.6)
project(project1)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

link_directories(/usr/X11R6/lib)

include_directories(/usr/share/X11)

set(SOURCE_FILES main.cpp)
add_executable(project1 ${SOURCE_FILES})

Upvotes: 1

Views: 5053

Answers (2)

Pierre
Pierre

Reputation: 2090

I won't be able to explain why (if you have some idea, don't hesitate to comment my answer), but, in my case, I had to link X11 library using this command:

target_link_libraries( DisplayImage "-lX11" )

It works, at least, for the 3.5.1 version of cmake.

Upvotes: 0

Amadeus
Amadeus

Reputation: 10655

In your case, you forgot to specify the libraries that cmake should use to link your application (target_link_libraries or link_libraries).

But, why not just let cmake find the required path, libraries and includes by itself? I suggest you to use find_package(X11). In your case, you can try:

cmake_minimum_required(VERSION 3.6)
project(project1)

set(CMAKE_CXX_STANDARD 11)  # for c++11

find_package(X11 REQUIRED)
link_libraries(${X11_LIBRARIES})
include_directories(${X11_INCLUDE_DIR})

set(SOURCE_FILES main.cpp)
add_executable(project1 ${SOURCE_FILES})

Upvotes: 9

Related Questions