爲了使用cmph,一個完美的最小哈希庫,在我使用CMake組織的項目中,我在一臺Ubuntu機器上安裝了cmph庫,並使用一個名爲c的文件main.c中如何在我的項目中使用CMake鏈接已編譯的cmph庫
如果我嘗試用gcc 5.3.0使用下面的命令編譯該文件:
gcc main.c
我會得到下面的輸出
/tmp/ccSOH5ob.o: In function `main':
testperfect.c:(.text+0x63): undefined reference to `cmph_io_vector_adapter'
testperfect.c:(.text+0x73): undefined reference to `cmph_config_new'
testperfect.c:(.text+0x88): undefined reference to `cmph_config_set_algo'
testperfect.c:(.text+0x9b): undefined reference to `cmph_config_set_mphf_fd'
testperfect.c:(.text+0xa7): undefined reference to `cmph_new'
testperfect.c:(.text+0xb7): undefined reference to `cmph_config_destroy'
testperfect.c:(.text+0xca): undefined reference to `cmph_dump'
testperfect.c:(.text+0xd6): undefined reference to `cmph_destroy'
testperfect.c:(.text+0xe2): undefined reference to `cmph_load'
testperfect.c:(.text+0x118): undefined reference to `cmph_search'
testperfect.c:(.text+0x153): undefined reference to `cmph_destroy'
testperfect.c:(.text+0x15f): undefined reference to `cmph_io_vector_adapter_destroy'
但是,如果我運行此命令:
gcc main.c $(pkg-config --libs cmph) -o main
它將被編譯並正常運行。
現在我需要添加一個類似的一段代碼在我的項目和CMakeList.txt是這樣寫的:
set(PROJECT_EXECUTABLE ${PROJECT_NAME})
# Compiling flags.
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR
CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
set(CMAKE_CXX_FLAGS_DEBUG "-g")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os")
endif()
# Inject project config.
configure_file(
${PROJECT_INCLUDE_DIR}/phsim/config.hpp.in
${PROJECT_INCLUDE_DIR}/phsim/config.hpp
)
include(FindPkgConfig)
find_package(PkgConfig REQUIRED)
pkg_search_module(CMPH REQUIRED cmph)
target_link_libraries(Phsim ${CMPH_LIBRARIES})
target_include_directories(Phsim PUBLIC ${CMPH_INCLUDE_DIRS})
target_compile_options(Phsim PUBLIC ${CMPH_CFLAGS_OTHER})
# Compile executable.
file(GLOB SOURCES ${PROJECT_SRC_DIR}/*.cpp)
add_executable(${PROJECT_EXECUTABLE} ${SOURCES})
set_target_properties(${PROJECT_EXECUTABLE} PROPERTIES
VERSION ${PHSIM_VERSION_LITER}
)
然後我嘗試運行cmake的。並只能得到錯誤信息:
CMake Error at src/CMakeLists.txt:20 (target_link_libraries):
Cannot specify link libraries for target "Phsim" which is not built by this
project.
但我不會得到目標可執行文件,除非我編譯項目。如果我嘗試編譯我的項目時沒有與庫鏈接相關的命令,編譯器會在我的問題開始時提供類似的鏈接錯誤。提前
https://cmake.org/Wiki/CMake:How_To_Find_Libraries
https://cmake.org/cmake/help/v3.6/module/FindPkgConfig.html
非常感謝:
我已經檢查了以下問題:
Undefined reference to cmph functions even after installing cpmh library
我試圖通過這些網站提供的說明。
'CMPH_LIBRARIES'的價值是什麼? – usr1234567
@ usr1234567它是/ usr/share/lib,我有.a和.so文件匹配模式libcmph *。* –
Phism沒有在任何地方聲明。你錯過了一個'add_executable'嗎?在嘗試將東西鏈接到它之前,應該定義它。你的自動add_executable代碼看起來很奇怪,我不會使用這樣的事情。它不是CMake風格。 – usr1234567