【问题标题】:Understanding writing a CMakeLists.txt [duplicate]了解编写 CMakeLists.txt [重复]
【发布时间】:2020-09-08 16:17:43
【问题描述】:

通过运行以下命令,我有以下代码可以与gcc完美配合:

gcc -L ~/Installed/C_LIBS/cmocka/lib -I ~/Installed/C_LIBS/cmocka/include hello.c -lcmocka -o hello 

当我尝试将其转换为 CMakeLists.txt 时,它会在运行 cd build && cmake .. && make 后中断,并出现以下错误代码:

Scanning dependencies of target hello
[ 50%] Building C object CMakeFiles/hello.dir/main.c.o
[100%] Linking C executable hello
ld: library not found for -lcmocka
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [hello] Error 1
make[1]: *** [CMakeFiles/hello.dir/all] Error 2
make: *** [all] Error 2

我有这样的代码设置:

    my-proj/
     - CMakeLists.txt
     - main.c
     - build/

这是我的文件:

main.c

    #include <stdarg.h>
    #include <stddef.h>
    #include <setjmp.h>
    #include <cmocka.h>
    /* A test case that does nothing and succeeds. */
    static void null_test_success(void **state) {
        (void) state; /* unused */
    }
    int main(void) {
        const struct CMUnitTest tests[] = {
            cmocka_unit_test(null_test_success),
        };
        return cmocka_run_group_tests(tests, NULL, NULL);
    }

CMakeLists.txt

    cmake_minimum_required(VERSION 2.8.9)
    project (hello)

    include_directories(
    SYSTEM ~/Installed/C_LIBS/cmocka/lib
    SYSTEM ~/Installed/C_LIBS/cmocka/include
    )

    add_executable(hello main.c)
    target_link_libraries(hello cmocka)

有人可以告诉我我在这里做错了什么吗?也可以指出我在哪里可以更好地学习 CMake?

【问题讨论】:

  • include_directories() 映射到-I,对-L没有影响
  • 什么映射到 -L ?
  • 干净的方法是使用find_library(),但由于您在 CMakeLists.txt 中硬编码了本地路径,因此您应该只链接库的绝对路径。 link_directories() 和 target_link_directories() 很少是正确答案。

标签: c++ c makefile cmake


【解决方案1】:

include_directories() 命令只影响标头搜索路径(通过#include 使用的东西)。它对库搜索路径没有影响。

由于您知道库的完整路径,因此您应该直接链接到所述完整路径:

 target_link_libraries(hello ~/Installed/C_LIBS/cmocka/lib/libcmocka.a)

但是,这只是修补您的 CMakeLists.txt。您应该做的是使用 CMake 的库函数,这将更加灵活:

# Include dir
find_path(MOCKA_INCLUDE_DIR
  NAMES cmocka.h
  PATHS ~/Installed/C_LIBS/cmocka/include
)

#library itself
find_library(MOCKA_LIBRARY
  NAMES cmocka
  PATHS ~/Installed/C_LIBS/cmocka/lib
)

target_include_directories(hello PRIVATE ${MOCKA_INCLUDE_DIR})
target_link_libraries(hello ${MOCKA_LIBRARY})

【讨论】:

  • 我现在在构建的 cmake 部分遇到了一些错误,但我想我开始明白你在说什么了。我非常感谢您的帮助。
  • 明白了!!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 2022-08-15
  • 2021-01-09
  • 1970-01-01
相关资源
最近更新 更多