为 c++ 构建一个静态库,该库在内部依赖于第三方库

Build a static library for c++ which is internally dependent on third-party libraries

本文关键字:在内部 第三方 依赖于 静态 一个 构建 c++      更新时间:2023-10-16

我想让图书馆说libmyfoo.a在一个位置/home/my/library/libmyfoo.a

我想以最简单的形式使用这个静态库,如下所示:

假设这是我的程序.cpp

#include "AAA.h"
int main(void) {
int x = 2;
myFooFunction(x);
return(0);
}

我想以g++ -std=c++11 -I/path/to/AAA.h myProgram.c -o myProgram -L/home/my/library/ -lmyfoo运行它

现在:AAA.h(和AAA.cc)依赖于第三方框架/库,即gstreamer,protobufgrpc

/path/to/AAA.h的层次结构是

Makefile
AAA.h
AAA.cc
AAA.o
BBB(Folder)
BBB.cc
BBB.h
BBB.o

生成文件具有以下规则:

GOOGLEAPIS_GENS_PATH ?= $(HOME)/GOOGLE/googleapis/gens
GOOGLEAPIS_API_CCS = $(shell find $(GOOGLEAPIS_GENS_PATH)/google/api 
-name '*.pb.cc')
GOOGLEAPIS_RPC_CCS = $(shell find $(GOOGLEAPIS_GENS_PATH)/google/rpc 
-name '*.pb.cc')
GOOGLEAPIS_SPEECH_CCS = $(shell find 
$(GOOGLEAPIS_GENS_PATH)/google/cloud/speech -name '*.pb.cc')
GOOGLEAPIS_LONGRUNNING_CCS = $(shell find 
$(GOOGLEAPIS_GENS_PATH)/google/longrunning -name '*.pb.cc')
GOOGLEAPIS_CCS = $(GOOGLEAPIS_API_CCS) $(GOOGLEAPIS_RPC_CCS) 
$(GOOGLEAPIS_LONGRUNNING_CCS) $(GOOGLEAPIS_SPEECH_CCS)

OBJS = ./BBB/BBB.o AAA.o
.PHONY: all
all: libmyfoo.a
libmyfoo.a: $(OBJS) $(GOOGLEAPIS_CCS:.cc=.o)
ar rcs $@ $(OBJS) $(GOOGLEAPIS_CCS:.cc=.o)
ranlib $@
echo "build final executable......"

这将构建包含大量*.o文件的libmyfoo.a

问题:当我尝试运行如上所示的myProgram.cpp时,它会抛出对很多事情的未定义引用。这意味着它没有正确链接。

现在AAA.ccBBB.cc依赖于grpc,protobuf和gstreamer,正如我所说。所以我myProgram.cpp链接了那些

g++ -std=c++11 -I/path/to/AAA.h myProgram.c -o myProgram -L/home/my/library/ -lmyfoo -L/usr/lib -L/usr/lib64 -L/usr/local/lib64 -L/usr/local/lib -lgrpc++ -lgrpc -lgrpc++_reflection -lprotobuf -lpthread -lglib-2.0 -lgobject-2.0 -lgstreamer-1.0 -ldl -lboost_system -lboost_thread

绝对可以正常工作

有人可以解释为什么吗? 而且是否可以myProgram.cpp前面提到的方式运行,即g++ -std=c++11 -I/path/to/AAA.h myProgram.c -o myProgram -L/home/my/library/ -lmyfoo

问候

当您使用的静态库依赖于共享库时,您需要将最终二进制文件显式链接到这些共享库。原因是静态库只是对象文件的集合,打包到"ar"存档中(这就是.a文件)。不存储有关共享库依赖项的信息。