我有以下代码 一帆风顺 与 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()
命令只影响头部搜索路径(通过 #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})