gpt4 book ai didi

c - Makefile LINK.cc - main.o 放在链接库之后并导致错误

转载 作者:行者123 更新时间:2023-11-30 14:48:20 28 4
gpt4 key购买 nike

我正在关注这个tutorial关于如何制作 makefile。我为我的项目做了一个如下。但是,链接阶段和文件顺序存在问题。

教程说 LINK.cc 使用 cxx,cxxflags、ldflags 定义为

$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)

命令行给出的输出表明 main.o 被放置在链接之后,而它应该在链接之前。

gcc  -I./include -I/usr/local/include/upm  -c -o utils.o utils.c
g++ -I./include -I/usr/local/include/upm -L/usr/local/lib/x86_64-linux-gnu -L/usr/local/lib/ -lrabbitmq -lupmc-rn2483 -lupmc-utilities -lupmc-rn2903 main.o utils.o -o myprogram

正确命令:

gcc main.o -I./include -I/usr/local/include/upm -L/usr/local/lib/x86_64-linux-gnu -L/usr/local/lib/ -lrabbitmq -lupmc-rn2483 -lupmc-utilities -lupmc-rn2903  utils.o  -o myprogram

我的问题是如何修复 makefile?

生成文件

program_NAME := myprogram
program_C_SRCS := $(wildcard *.c)

program_CXX_SRCS := $(wildcard *.cpp)

program_C_OBJS := ${program_C_SRCS:.c=.o}

program_CXX_OBJS := ${program_CXX_SRCS:.cpp=.o}

program_OBJS := $(program_C_OBJS) $(program_CXX_OBJS)

program_INCLUDE_DIRS := ./include /usr/local/include/upm

program_LIBRARY_DIRS := /usr/local/lib/x86_64-linux-gnu /usr/local/lib/

program_LIBRARIES := rabbitmq upmc-rn2483 upmc-utilities upmc-rn2903

CPPFLAGS += $(foreach includedir,$(program_INCLUDE_DIRS),-I$(includedir))
LDFLAGS += $(foreach librarydir,$(program_LIBRARY_DIRS),-L$(librarydir))
LDFLAGS += $(foreach library,$(program_LIBRARIES),-l$(library))

CC = gcc
CXX = g++

LINK.o = $(CC) $(LDFLAGS) $(TARGET_ARCH)

LINK.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)

.PHONY: all clean distclean

all: $(program_NAME)

$(program_NAME): $(program_OBJS)
$(LINK.cc) $(program_OBJS) -o $(program_NAME)


clean:
@- $(RM) $(program_NAME)
@- $(RM) $(program_OBJS)

distclean: clean

这是目录结构:

.
├── include
│   └── utils.h
├── main.c
├── Makefile
└── utils.c

最佳答案

不要将库 (-l) 放入 LDFLAGS 中,而是将它们放入 LDLIBS 中。 make使用的链接规则是:

$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@

对 makefile 的更改是

LDLIBS += $(foreach library,$(program_LIBRARIES),-l$(library))
[...]
$(LINK.cc) $(program_OBJS) -o $(program_NAME) $(LDLIBS)

关于c - Makefile LINK.cc - main.o 放在链接库之后并导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473119/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com