Makefile 中 main 的多重定义

Multiple definition of main in Makefile

我正在尝试使用 ./obj./obj_prof 中的对象从 ./src 中的源生成文件 ppm2jpeg。我还想生成可以在 ./tests.

中独立执行的测试

这是我的主文件夹中的 Makefile:

CC = gcc
LD = gcc


CFLAGS = -Wall -Wextra -std=c99 -Iinclude -Ofast -pg
LDFLAGS = -lm -pg


SRC_FILES=$(wildcard src/*.c)



OBJ_FILES=$(patsubst src/%.c,obj/%.o,$(SRC_FILES))

OBJ_PROF_FILES = obj_prof/htables_prof.o

all: ppm2jpeg tests

ppm2jpeg: $(OBJ_FILES) $(OBJ_PROF_FILES)
    $(LD) $(OBJ_FILES) $(OBJ_PROF_FILES) $(LDFLAGS) -o $@

tests: $(OBJ_FILES) $(OBJ_PROF_FILES)
    make -C tests/

obj/%.o: src/%.c
    $(CC) -c $(CFLAGS) $< -o $@


clean:
    rm -rf ppm2jpeg do_test $(OBJ_FILES)
    make -C tests/ clean
    rm -f $(wildcard images/*.bla)
    rm -f $(wildcard images/*.jpg)

这是我在 ./tests 中的 Makefile:

CC = gcc
LD = gcc


CFLAGS = -Wall -Wextra -std=c99 -I../include -O0 -g
LDFLAGS = -lm -pg

OBJ_FILES = $(wildcard ../obj/*.o)
OBJ_PROF_FILES = ../obj_prof/htables_prof.o


SRC_TESTS = $(wildcard *-test.c)
OBJ_TESTS = $(patsubst %.c,%.o,$(SRC_TESTS))
TESTS = $(patsubst %-test.c,%-test,$(SRC_TESTS))

all: $(TESTS)

%-test: %-test.o
    $(CC) -g $(OBJ_FILES) $(OBJ_PROF_FILES) $(OBJ_TEST) $^ -o $@ $(LDFLAGS)

%-test.o: %-test.c
    $(CC) $(CFLAGS) -lm -c $^

clean:
    rm -rf *.o *~ $(TESTS)
CC = gcc
LD = gcc


CFLAGS = -Wall -Wextra -std=c99 -I../include -O0 -g
LDFLAGS = -lm -pg

OBJ_FILES = $(wildcard ../obj/*.o)
OBJ_PROF_FILES = ../obj_prof/htables_prof.o

# Fichiers de test
SRC_TESTS = $(wildcard *-test.c)
OBJ_TESTS = $(patsubst %.c,%.o,$(SRC_TESTS))
TESTS = $(patsubst %-test.c,%-test,$(SRC_TESTS))

all: $(TESTS)

%-test: %-test.o
    $(CC) -g $(OBJ_FILES) $(OBJ_PROF_FILES) $(OBJ_TEST) $^ -o $@ $(LDFLAGS)

%-test.o: %-test.c
    $(CC) $(CFLAGS) -lm -c $^

clean:
    rm -rf *.o *~ $(TESTS)
CC = gcc
LD = gcc


CFLAGS = -Wall -Wextra -std=c99 -I../include -O0 -g
LDFLAGS = -lm -pg

OBJ_FILES = $(wildcard ../obj/*.o)
OBJ_PROF_FILES = ../obj_prof/htables_prof.o

# Fichiers de test
SRC_TESTS = $(wildcard *-test.c)
OBJ_TESTS = $(patsubst %.c,%.o,$(SRC_TESTS))
TESTS = $(patsubst %-test.c,%-test,$(SRC_TESTS))

all: $(TESTS)

%-test: %-test.o
    $(CC) -g $(OBJ_FILES) $(OBJ_PROF_FILES) $(OBJ_TEST) $^ -o $@ $(LDFLAGS)

%-test.o: %-test.c
    $(CC) $(CFLAGS) -lm -c $^

clean:
    rm -rf *.o *~ $(TESTS)

当我尝试这样做时

/tests/example-test.c:5: multiple definition of `main'; ../obj/ppm2jpeg.o:ppm2jpeg.c:(.text.startup+0x0): first defined here
collect2: error: ld returned 1 exit status

该错误消息表示您正在尝试 link 两个目标文件,每个目标文件都包含一个 main() 函数。

分析错误信息,我猜想 example-test.cppm2jpeg.c 都定义了 main(),这意味着你不应该 link example-test.oppm2jpeg.o 在同一个可执行文件中。

在你的 Makefile 中,你可能应该确保 OBJ_FILES 只列出没有定义 main() 的文件,所以你应该确保它遗漏了 ppm2jpeg.o.