C语言 如何使用 CMake 链接到 C 数学库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34625627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:17:30  来源:igfitidea点击:

How to link to the C math library with CMake?

ccmake

提问by phillipsK

How do I add the mathlibrary to my CMake file? This postreferences adding a target link library, yet I am not too familiar with C. An Additional post- Could someone please demonstrate an example. DocumentationI am using C and I receive an undefined reference to 'pow'with the pow method of the math header.

如何将math库添加到我的 CMake 文件中?这篇文章引用了添加目标链接库,但我对 C 不太熟悉。 一个附加的帖子- 有人可以演示一个例子。文档我正在使用 C 并且我收到一个undefined reference to 'pow'带有数学标题的 pow 方法的文件。

cmake_minimum_required(VERSION 3.3)
project(CSCI-E-28-Unix-Linux-Systems-Programming)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES
    CMakeLists.txt
    getchar.c
    main.cpp
        hw0
    more01.c)

#target_link_libraries(<math.h> m)

add_executable(main main.cpp)
add_executable(getchar getchar.c)
add_executable(more01 more01.c)
add_executable(argu print_all_arguments.c)
add_executable(chars chars.c)
add_executable(ch4 ch4.c)

回答by usr1234567

Many mathematical functions (pow, sqrt, fabs, logetc.) are declared in math.hand require the library libmto be linked. Unlike libc, which is automatically linked, libmis a separate library and often requires explicit linkage. The linker presumes all libraries to begin with lib, so to link to libmyou link to m.

许多数学函数(powsqrtfabslog等)中声明math.h,并要求该库libm被链接。与libc自动链接的不同,它是libm一个单独的库,通常需要显式链接链接器假定所有库都以 开头lib,因此链接到libm您链接到m.

You have to use it like target_link_libraries(ch4 m)to link libmto your target. The first argument must be a target. Thus it must be used after add_executable(ch4 ch4.c)like:

您必须像target_link_libraries(ch4 m)链接libm到目标一样使用它。第一个参数必须是目标。因此它必须在add_executable(ch4 ch4.c)like之后使用:

add_executable(ch4 ch4.c)
target_link_libraries(ch4 m)