如何使用 CMake 链接到 C 数学库? [英] How to link to the C math library with CMake?
问题描述
如何将 math
库添加到我的 CMake 文件中?这个 post 引用添加了一个 目标链接库,但我对 C 不太熟悉.附加帖子 - 有人可以演示一个例子.文档 我正在使用 C 并且我收到一个 undefined使用数学标题的 pow 方法引用 'pow'
.
How do I add the math
library to my CMake file? This post references adding a target link library, yet I am not too familiar with C. An Additional post - Could someone please demonstrate an example. Documentation I am using C and I receive an undefined reference to 'pow'
with the pow method of the math header.
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)
推荐答案
许多数学函数(pow
、sqrt
、fabs
、>log
等)在 math.h
和 中声明需要链接库 libm
.与自动链接的 libc
不同,libm
是一个单独的库,通常 需要显式链接.链接器假定所有库都以lib
,所以要链接到 libm
你链接到 m
.
Many mathematical functions (pow
, sqrt
, fabs
, log
etc.) are declared in math.h
and require the library libm
to be linked. Unlike libc
, which is automatically linked, libm
is a separate library and often requires explicit linkage. The linker presumes all libraries to begin with lib
, so to link to libm
you link to m
.
你必须像 target_link_libraries(ch4 m)
一样使用它来将 libm
链接到你的目标.第一个参数必须是一个目标.因此它必须在 add_executable(ch4 ch4.c)
之后使用,如:
You have to use it like target_link_libraries(ch4 m)
to link libm
to your target. The first argument must be a target. Thus it must be used after add_executable(ch4 ch4.c)
like:
add_executable(ch4 ch4.c)
target_link_libraries(ch4 m)
这篇关于如何使用 CMake 链接到 C 数学库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!