我在编译程序以使用 ncurses 时遇到一些问题。我是创建 makefile 的新手,所以:
这是我的 makefile:
test_reservation: reservation.o service.o
gcc -g -m32 service.o reservation.o -o test_reservation
service.o: service.c
gcc -g -m32 -c -o service.o service.c -std=c99 -lncurses
reservation.o: reservation.s
as -gdbb --32 -o reservation.o reservation.s
我已经安装并包含在我的 c 文件中
当我试图做到这一点时:
gcc -g -m32 service.o reservation.o -o test_reseration
service.o: In function `main':
/home/xxx/reservationService/service.c:23: undefined reference to `initscr'
collect2: error: ld returned 1 exit status
makefile:2: recipe for target 'test_reservation' failed
make: *** [test_reservation] Error 1
这个 makefile 有什么问题?我该如何编译它?
最佳答案
这里有一个更好的 Makefile 框架供您引用:
PKGS := ncursesw
CC := gcc
CFLAGS := -Wall -m32 -O2 -std=c99 $(shell pkg-config --cflags $(PKGS))
LDFLAGS := $(shell pkg-config --libs $(PKGS))
AS := as
ASFLAGS := -gdbb --32
PROGS := test-reservation
.PHONY: all clean
all: $(PROGS)
clean:
$(RM) *.o $(PROGS)
%.o: %.c
$(CC) $(CFLAGS) -c $^ -o $@
%.o: %.s
$(AS) $(ASFLAGS) $^ -o $@
test-reservation: reservation.o service.o
$(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
如果您复制粘贴以上内容,请记住运行 sed -e 's|^ *|\t|' -i Makefile
修复缩进。
大多数 Linux 发行版使用 pkg-config
跟踪编译特定库所需的选项。你只需要把你需要的包添加到 PKGS
变量,用空格分隔。 ncursesw
是支持宽字符的 ncurses 版本(您需要 Unicode 字符输出)。 $(shell pkg-config ... $(PKGS))
习语使用 pkg-config
shell 命令来提取正确的标志 ( --cflags
) 和库文件 ( --libs
)。
如果您使用<math.h>
,你需要在前面加上 -lm
至LDFLAGS
;即LDFLAGS := -lm $(shell pkg-config --libs $(PKGS))
.
如果您在该目录中编译多个二进制文件,只需将最终的二进制文件名称添加到 PROGS
,并添加新规则,例如
foo-bin: foo.o bar.o baz.o
$(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
规则操作不会改变,只有目标和先决条件发生变化。
与 all: $(PROGS)
规则,你只需要运行make
编译 PROGS
中命名的所有二进制文件。如果你修改说 service.c
,然后都是 service.o
和test-reservation
将被重新编译。运行make clean all
删除所有已编译的文件,然后重新编译它们。
关于c - Makefile .c + .as 与 ncurses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50494850/