未定义的引用 grpc 和 protobuf 错误 - C++

Undefined reference grpc and protobuf error - C++

我正在编写两个实体(媒人和宿主)之间的 grpc 通信代码。我的 makefile 如下所示:

CXX = g++
LDFLAGS +=  `pkg-config --cflags --libs protobuf grpc grpc++`\
           -lgrpc++_reflection\
           -ldl


host: comm hosts/host.cc hosts/host.h
    $(CXX) $(LDFLAGS) hosts/host.cc build/matchmaker.grpc.pb.o build/matchmaker.pb.o -g -o build/host.o

comm: comm/matchmaker.grpc.pb.cc comm/matchmaker.grpc.pb.h comm/matchmaker.pb.cc comm/matchmaker.pb.h
    $(CXX) $(LDFLAGS) comm/matchmaker.grpc.pb.cc -g -c -o build/matchmaker.grpc.pb.o
    $(CXX) $(LDFLAGS) comm/matchmaker.pb.cc -g -c -o build/matchmaker.pb.o

我收到多个 grpc 和 protobuf class 代码的未定义引用错误。部分错误如下所示:

/usr/bin/ld: /tmp/cciFPkpo.o: in function `Host::RegisterHost()':
~/Projects/p1/hosts/host.cc:11: undefined reference to `grpc::ClientContext::ClientContext()'
/usr/bin/ld: ~/Projects/p1/hosts/host.cc:11: undefined reference to `grpc::ClientContext::~ClientContext()'
/usr/bin/ld: ~/Projects/p1/hosts/host.cc:11: undefined reference to `grpc::ClientContext::~ClientContext()'
/usr/bin/ld: /tmp/cciFPkpo.o: in function `main':
~/Projects/p1/hosts/host.cc:27: undefined reference to `grpc::InsecureChannelCredentials()'
.
.
.

~/Projects/p1/hosts/../comm/matchmaker.pb.h:895: undefined reference to `google::protobuf::RepeatedField<float>::Set(int, float const&)'

pkg-config --cflags --libs protobuf grpc grpc++ 的输出如下:

-DNOMINMAX -maes -msse4.1 -DNOMINMAX -maes -msse4.1 -DNOMINMAX -I~/grpc/include -L~/grpc/lib -lprotobuf -pthread -lgrpc++ -lgrpc -laddress_sorting -lre2 -lupb -lcares -lz -lgpr -lssl -lcrypto -labsl_raw_hash_set -labsl_hashtablez_sampler -labsl_hash -labsl_city -labsl_low_level_hash -labsl_random_distributions -labsl_random_seed_sequences -labsl_random_internal_pool_urbg -labsl_random_internal_randen -labsl_random_internal_randen_hwaes -labsl_random_internal_randen_hwaes_impl -labsl_random_internal_randen_slow -labsl_random_internal_platform -labsl_random_internal_seed_material -labsl_random_seed_gen_exception -labsl_statusor -labsl_status -labsl_cord -labsl_cordz_info -labsl_cord_internal -labsl_cordz_functions -labsl_exponential_biased -labsl_cordz_handle -labsl_bad_optional_access -labsl_str_format_internal -labsl_synchronization -labsl_graphcycles_internal -labsl_stacktrace -labsl_symbolize -labsl_debugging_internal -labsl_demangle_internal -labsl_malloc_internal -labsl_time -labsl_civil_time -labsl_strings -labsl_strings_internal -lrt -labsl_base -labsl_spinlock_wait -labsl_int128 -labsl_throw_delegate -labsl_time_zone -labsl_bad_variant_access -labsl_raw_logging_internal -labsl_log_severity

grpc 和 protobuf 之前是通过软件中心安装的,我删除了。目前的grpc和protobuf都是从源码构建的

我不确定如何解决未定义的引用错误。任何指针都会非常有帮助。提前致谢。

您需要将 $(LDFLAGS) 移动到 之后 依赖于它的目标文件:

host: comm hosts/host.cc hosts/host.h
    $(CXX) hosts/host.cc build/matchmaker.grpc.pb.o build/matchmaker.pb.o -g -o build/host $(LDFLAGS)