Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify the include directory for an imported shared library using CMake?

Tags:

cmake

I am using cmake version 3.9.1.

I have a third party shared library and header file in my source tree. I am trying to add it as a link target.

All the documentation I can find says that this should work:

test.cpp

#include "ftd2xx.h"

int main(int argc, char **argv)
{
    FT_HANDLE handle;
    FT_STATUS status = FT_Open(1, &handle);

    return 0;
}

CMakeLists.txt

cmake_minimum_required (VERSION 3.6)
project(test_proj CXX)
add_subdirectory(ftdi)
add_executable(mytest test.cpp)
target_link_libraries(mytest ftd2xx)

ftdi/CMakeLists.txt

add_library(ftd2xx SHARED IMPORTED)
set_target_properties(ftd2xx PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(ftd2xx PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR})

However compiling test.cpp, which includes "ftd2xx.h", complains that it cannot find the header file and the relevant -I<path> entry is missing from the generated makefiles.

If I specify the library as INTERFACE rather than SHARED IMPORTED then the header file is found correctly, but CMake barfs on setting the IMPORTED_LOCATION property.

If I specify the library as INTERFACE rather than SHARED IMPORTED and then use target_link_libraries to point directly to the library file than this works for Windows but not for Linux.

I'd appreciate any help anyone can offer.

like image 945
AlastairG Avatar asked Sep 22 '17 09:09

AlastairG


1 Answers

The CMake documentation does actually answer this one, but so concisely, and in the middle of a much larger paragraph, that it is easy to miss:

The target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility.

I am using the target name in a higher level directory, so I need to declare the library as SHARED IMPORTED GLOBAL rather than just SHARED IMPORTED.

Final code is:

add_library(ftd2xx SHARED IMPORTED GLOBAL)
set_target_properties(ftd2xx PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR})

And then for Windows:

    set_target_properties(ftd2xx PROPERTIES IMPORTED_IMPLIB ${CMAKE_CURRENT_SOURCE_DIR}/win32/ftd2xx.lib)
    set_target_properties(ftd2xx PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/win32/ftd2xx.dll)

And for Linux:

    set_target_properties(ftd2xx PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/i386/libftd2xx.so)
like image 164
AlastairG Avatar answered Nov 15 '22 07:11

AlastairG