CMake 无法 link 可执行文件 -ljsoncpp: 没有这样的文件

CMake cannot link executable -ljsoncpp: no such file

我在一个项目中工作,该项目使用 jsoncpp 进行解析并使用 cmake 进行编译。我使用 git submodule add REPO_URL external/jsoncpp 将 jsoncpp 官方 git repository 作为子模块添加到我的项目中,以便将所有依赖项放在一起。

运行cmake -B out/build时正常。但是当我执行 make 时,出现以下错误:

/usr/bin/ld: cannot find -ljsoncpp: No such file or directory.

文件按以下方式组织:

- root
    - out/build
    - external
        - jsoncpp (cloned repo)
    - include
        foo.h
        bar.h
    - src
        foo.cpp
        bar.cpp
        main.cpp
    CMakeLists.txt

CMakeLists.txt是这样的:

cmake_minimum_required(VERSION 3.22.1)
project(ants)


# ".cpp" files in folder "src" into cmake variable "SOURCE"
file(GLOB SOURCE "src/*.cpp")

# Executable
add_executable(${PROJECT_NAME} ${SOURCE})

# Directory where cmake will look for include files
include_directories(include)

# Tells cmake to compile jsoncpp
add_subdirectory(external/jsoncpp)
# Tells cmake where to look for jsoncpp include files
target_include_directories(${PROJECT_NAME} 
    PUBLIC external/jsoncpp/include 
)

target_link_libraries(${PROJECT_NAME} jsoncpp)

jsoncppConfig.cmake 为目标 jsoncpp_libjsoncpp_lib_static 定义了 属性 INTERFACE_INCLUDE_DIRECTORIES

您需要查询目标属性并手动设置:

get_target_property(JSON_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${JSON_INC_PATH})

链接通过以下方式完成:

target_link_libraries(${PROJECT_NAME} jsoncpp_lib)

Source.

试试这个:

cmake_minimum_required(VERSION 3.22.1)
project(ants)

# ".cpp" files in folder "src" into cmake variable "SOURCE"
file(GLOB SOURCE "src/*.cpp")

# Executable
add_executable(${PROJECT_NAME} ${SOURCE})

# Directory where cmake will look for include files
include_directories(include)

# Tells cmake to compile jsoncpp
add_subdirectory(external/jsoncpp)
get_target_property(JSON_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${JSON_INC_PATH})

target_link_libraries(${PROJECT_NAME} jsoncpp_lib)