C++ 了解如何编写CMakeLists.txt
我有以下代码,通过运行命令,可以与C++ 了解如何编写CMakeLists.txt,c++,c,makefile,cmake,C++,C,Makefile,Cmake,我有以下代码,通过运行命令,可以与gcc完美地工作: gcc -L ~/Installed/C_LIBS/cmocka/lib -I ~/Installed/C_LIBS/cmocka/include hello.c -lcmocka -o hello 当我尝试将其转换为CMakeLists.txt时,在运行cd build&&cmake..&&使用以下错误代码生成: Scanning dependencies of target hello [ 50%] Building C object
gcc
完美地工作:
gcc -L ~/Installed/C_LIBS/cmocka/lib -I ~/Installed/C_LIBS/cmocka/include hello.c -lcmocka -o hello
当我尝试将其转换为CMakeLists.txt
时,在运行cd build&&cmake..&&使用以下错误代码生成
:
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);
}
有人能告诉我我做错了什么吗?还可以告诉我在哪里可以更好地学习CMake?该
包含目录()
命令只影响标题搜索路径(通过\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})
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})
include_directories()映射到
-I
,它对-L
映射到-L的内容没有影响?干净的方法是使用find_library()
,但是由于您在CMakeLists.txt中硬编码了本地路径,因此您应该只链接到库的绝对路径link\u directories()
和target\u link\u directories()
很少是正确的答案。include\u directories()映射到-I
,它对-L
映射到-L的内容没有影响。干净的方法是使用find\u library()
,但是由于您在CMakeLists.txt中硬编码了本地路径,您应该只针对库的绝对路径进行链接link\u directories()
和target\u link\u directories()。我真的很感谢你的帮助。明白了!!非常感谢你!!我现在在构建的cmake部分遇到了一些错误,但我想我已经开始理解您的意思了。我真的很感谢你的帮助。明白了!!非常感谢你!!