文件是为不受支持的文件格式构建的,而不是链接的体系结构(x86_64)

7 macos gcc makefile gnu-make

我在OSX Lion上有一个构建文件

VPATH = src include
CFLAGS ="-I include -std=gnu99"

hello: hello.o
    gcc $^ -o $@

hello.o: hello.h hello.c
    gcc $(CFLAGS) -c $< -o $@
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行此make文件时,我收到以下错误

    ld: warning: ignoring file hello.o, file was built for unsupported file format which is not the architecture being linked (x86_64)
Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我已尝试使用该标志-arch x86_64但仍然得到相同的错误.

运行arch命令给出:i386.

uname -a 告诉我: Darwin Kernel Version 11.3.0: Thu Jan 12 18:47:41 PST 2012; root:xnu-1699.24.23~1/RELEASE_X86_64 x86_64

我还尝试添加交换机-march=x86-64,如本答案文件中所述是为i386构建的,这不是在Mac OSX 10.6上为iOS 4.2编译OpenCV2.2时所链接的架构(x86_64),但这对我没有用.

命令行的输出是:

gcc -I include -std=gnu99 -m64  -c include/hello.h -o hello.o  
gcc -I include -std=gnu99 -m64  hello.o -o hello
ld: warning: ignoring file hello.o, file was built for unsupported file format which is not the architecture being linked (x86_64)
Undefined symbols for architecture x86_64:
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [hello] Error 1
Run Code Online (Sandbox Code Playgroud)

Jon*_*ler 4

  1. 删除所有目标文件。
  2. 修改 makefile 更像:

    VPATH   = src include
    CFLAGS  = -I include -std=gnu99 -m64
    CC      = gcc
    LDLIBS  =
    LDFLAGS =
    
    hello: hello.o
        $(CC) $(CFLAGS) $^ -o $@
    
    hello.o: hello.c hello.h
        $(CC) $(CFLAGS) -c $< -o $@ $(LDFLAGS) $(LDLIBS)
    
    Run Code Online (Sandbox Code Playgroud)

请注意,我已经对命令行上的所有内容进行了宏化。CFLAGS 用于所有编译。它们没有用双引号引起来。该-m64选项请求 64 位版本;它不应该是必要的,但它使它变得明确。您还不需要 LDFLAGS 或 LDLIBS 宏(因此您可以省略它们而不会给自己带来问题),但它们显示了当您在链接时确实需要某些库时可以如何进行。

对于我自己的 makefile,我会执行以下操作:

IFLAGS = -Iinclude
WFLAG1 = -Wall
WFLAG2 = -Werror
WFLAG3 = -Wextra
WFLAGS = $(WFLAG1) $(WFLAG2) $(WFLAG3)
OFLAGS = -g -O3
SFLAG1 = -std=c99
SFLAG2 = -m64
SFLAGS = $(SFLAG1) $(SFLAG2)
DFLAGS = # -Doptions
UFLAGS = # Set on make command line only
CFLAGS = $(SFLAGS) $(DFLAGS) $(IFLAGS) $(OFLAGS) $(WFLAGS) $(UFLAGS)
Run Code Online (Sandbox Code Playgroud)

这样我就可以在命令行上调整 C 编译器的任何单个参数。例如,要进行 32 位构建,我可以运行:

make SFLAG2=-m32
Run Code Online (Sandbox Code Playgroud)

等等。缺点是我永远记不起哪个xFLAGn选项影响哪个。然而,快速查看一下 makefile 就可以纠正这个问题,并且我可以更改编译而不需要修改 makefile。

(我也经常CC="gcc -m64"在其他人的软件上强制进行 64 位编译。)