【问题标题】:GCC error undefined reference to `sqrt' on changing command option order [duplicate]在更改命令选项顺序时,GCC 错误未定义对“sqrt”的引用 [重复]
【发布时间】:2021-06-18 22:42:26
【问题描述】:

为什么会出现以下错误

/tmp/ccuWdVB3.o: In function `test':
MyCode.c:(.text+0x1c): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

MyCode.c

#include<stdio.h>
#include<math.h>

int test(int input1)
{

  int x = 8;
  int z = sqrt(x);
    
}

int main(int argc, char * a[]) {

}

使用命令运行时:

gcc -o a.out -lm MyCode.c

但是当我运行命令时

gcc MyCode.c -o a.out -lm

一切正常。为什么“MyCode.c”cli 选项的顺序在这里很重要? 还是我做错了什么?

【问题讨论】:

  • 你做对了,由于“历史原因”,订单很重要。我认为他们现在只是避免出于怀旧而修复它
  • -lm 使 gcc 在该库中查找它在命令行中需要的东西......所以gcc -o a.out -lm 不需要数学库中的任何东西......和gcc -o a.out -lm MyCode.c编译 MyCode.c 时不使用该库。 TLDR 始终在命令行末尾添加库:gcc -std=c11 -pedantic -Wall -Wextra -O... -f... -o executable *.c -l...
  • 这也花费了我很多时间 :) 但是不幸的是顺序确实很重要

标签: c gcc sqrt math.h


【解决方案1】:

在链接过程中只搜索一次库(它们可能包含数百万个符号和对象),这就是为什么当链接器必须搜索的所有对象都已知时,它们应该被指定为最后一个的原因。在项目中的每个目标文件之后在巨型库中搜索符号将非常低效。

【讨论】:

  • 原来是这样,但还是执行的问题吧?
  • gcc 是否保证它从左到右处理命令?
  • @Lundin 我认为是的:(来自 gcc 文档)"It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded."
  • 啊哈,很好。我认为这只是 gcc 中许多未记录的内容之一。
猜你喜欢
  • 2012-02-05
  • 2016-03-29
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
相关资源
最近更新 更多