在Makefile中未定义对`le16toh'错误的引用

时间:2018-11-08 22:52:32

标签: c makefile fat32

我正在尝试使用以下Makefile编译C程序:

msh: libFAT32.so
    gcc -Wall -fPIC -I. -o msh newTest.c -L. -lFAT32

libFAT32.so: 
    gcc -std=c99 -shared -o libFAT32.so -fPIC fat32.c

clean: 
    rm *.so msh

但是,每次我尝试使用make编译程序时,都会出现以下错误:

user@user-VirtualBox:~/fat1$ make
    gcc -Wall -fPIC -I. -o msh newTest.c -L. -lFAT32
    ./libFAT32.so: undefined reference to `le32toh'
    ./libFAT32.so: undefined reference to `le16toh'
    collect2: error: ld returned 1 exit status
    Makefile:19: recipe for target 'msh' failed
    make: *** [msh] Error 1

有人可以告诉您如何解决此问题吗?

1 个答案:

答案 0 :(得分:2)

所以,这就是正在发生的事情(假设您在VM中使用的是Linux发行版是安全的假设)。

使用此测试程序:

#include <stdio.h>
#include <endian.h>

int main(void) {
  printf("%d\n", le32toh(1234));
  return 0;
}

编译并运行它可以正常工作:

$ gcc -Wall -Wextra test.c
$ ./a.out
1234

但是,您正在使用-std=c99进行编译。因此,我们尝试一下:

$ gcc -std=c99 -Wall -Wextra test.c
test.c: In function ‘main’:
test.c:5:18: warning: implicit declaration of function ‘le32toh’ [-Wimplicit-function-declaration]
   printf("%d\n", le32toh(1234));
                  ^~~~~~~
/tmp/cc7p3cO8.o: In function `main':
test.c:(.text+0xf): undefined reference to `le32toh'
collect2: error: ld returned 1 exit status

c99模式下进行编译会禁用一堆函数和宏,除非明确请求,否则它们不会在C标准的1999版中使用,因此隐式声明警告。 le32toh()是一个宏,不是libc中带有符号的函数,因此链接器错误。

如果您阅读le32toh()的{​​{3}},将会看到它需要_DEFAULT_SOURCE man page,必须在包含任何标题之前对其进行定义。

因此,您的选择是:

  1. 改为以gnu99模式编译,因为这会自动定义一堆功能测试宏。
  2. 继续使用c99模式,并在fat32.c源文件的开头添加一个#define _DEFAULT_SOURCE
  3. 继续使用c99模式,并将-D_DEFAULT_SOURCE添加到编译器参数中。