简体   繁体   English

如何用Gnu make编写库?

[英]How to compose libraries with Gnu make?

I'm trying to create a library, called Aa, that provides a class A, which depends on the classes B and C, all in their respective files ( .cpp and .hpp ). 我正在尝试创建一个名为Aa的库,该库在它们各自的文件( .cpp.hpp )中提供了一个类A,该类取决于类B和C。 I usually compiled all my code manually, but as the number of files increased, I wanted to use a makefile. 我通常会手动编译所有代码,但是随着文件数量的增加,我想使用makefile。 Basically, what I would do was: 基本上,我要做的是:

g++ -c A.cpp
g++ -c B.cpp
g++ -c C.cpp
ar rvs A.a *.o

How can I construct a makefile that does this? 如何构造一个可以做到这一点的makefile? Can makefiles even call ar ? makefile甚至可以调用ar吗?

This is what I tried: 这是我尝试的:

CC=g++
CFLAGS=-c -Wall
objects=C.o B.o

all : A.o $(objects) #Creates the library called A.a.
:ar rvs A.a A.o $(objects)

A.o : $(objects) A.hpp A.cpp
:$(CC) $(CFLAGS) A.cpp

B.o : B.hpp B.cpp
:$(CC) $(CFLAGS) B.cpp

C.o : C.hpp C.cpp
:$(CC) $(CFLAGS) C.cpp

But it seems that my ar rvs Aa Ao $(objects) instruction isn't even executing. 但是,似乎我的ar rvs Aa Ao $(objects)指令甚至没有执行。 This makefile produces all the correct .o files, but doesn't archive them. 此makefile会生成所有正确的.o文件,但不会将它们存档。

You could use rules and patterns to make it more generic: 您可以使用规则和模式使其更通用:

SRC_DIR = .
CPPFLAGS += -g
INCLUDES = -I.

# variant 1
SRCS ?= $(shell find $(SRC_DIR) -name '*.cpp' | sed "s/[^\/]*\/[^\/]*\///")
# variant 2
SRCS = A.cpp B.cpp

%.o : $(SRC_DIR)/%.cpp
    $(CXX) -o $@ $(INCLUDES) $(CPPFLAGS) -c $^

all : A.a

A.a : $(SRCS:.cpp=.o) 
    $(AR) rsv $@ $^

OK, so my syntax was correct after all, or, at least, a big portion of it was. 好的,所以我的语法毕竟是正确的,或者至少是很大一部分。 I went with a wrong premise that : 's could replace tabs, which is, apparently, not correct after all. 我错了一个前提:可以替换制表符,这显然是不正确的。

So, this is the code that does what I want: 因此,这是执行我想要的代码:

CC=g++
CFLAGS=-c -Wall
objects=B.o C.o

all : A.a

A.o : $(objects) A.hpp A.cpp
    $(CC) $(CFLAGS) A.cpp

B.o : B.hpp B.cpp
    $(CC) $(CFLAGS) B.cpp

C.o : C.hpp C.cpp
    $(CC) $(CFLAGS) C.cpp

A.a : A.o $(objects)
    ar rvs A.a A.o $(objects)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM