1. 程式人生 > >cmake的INCLUDE_DIRECTORIES命令不起作用

cmake的INCLUDE_DIRECTORIES命令不起作用

按照《CMake Practice》中第六章的設定,採用INCLUDE_DIRECTORIES命令去尋找共享庫的路徑,src/CMakeLists.txt如下:

ADD_EXECUTABLE(main main.c)
INCLUDE_DIRECTORIES(/tmp/include/hello)
LINK_DIRECTORIES(/tmp/lib/)
TARGET_LINK_LIBRARIES(main libhello.a)

執行cmake及make後,仍然有link error。

cmake的官網對include_directories的說明如下:

*Specify directories in which the linker will look for libraries.

link_directories(directory1 directory2 …)

Note that this command is rarely necessary. Library locations returned by find_package() and find_library() are absolute paths. Pass these absolute library file paths directly to the target_link_libraries() command. CMake will ensure the linker finds them.*

官網不推薦使用link_directoris,而是推薦使用find_package和find_library尋找共享庫的絕對路徑,再傳給target_link_libraries使用。

按照這裡的例子,改寫了src/CMakeLists.txt如下:

ADD_EXECUTABLE(main main.c)
INCLUDE_DIRECTORIES(/tmp/include/hello)

find_library(LIBHELLO_PATH hello /tmp/lib)
IF(NOT LIBHELLO_PATH)
MESSAGE(FATAL_ERROR "libhello not found"
) ENDIF(NOT LIBHELLO_PATH) MESSAGE(STATUS ${LIBHELLO_PATH} " found") TARGET_LINK_LIBRARIES(main ${LIBHELLO_PATH})

這下可以編譯通過了。