Makefile 和 Boost URL:编译时对某些函数进行多重定义

Makefile and Boost URLS: Multiple definition of some function on compilation

提问人:Warren Niles 提问时间:12/8/2022 更新时间:12/8/2022 访问量:101

问:

基本上main.cpp依赖于服务器.cpp中的函数。所以main包括server.hpp,server.cpp也需要包括server.hpp。Server.hpp 包括 boost::urls,包括:

服务器.hpp

#ifndef _SERVER_H_
#define _SERVER_H_
...
#include <boost/url/src.hpp>
...
#endif

问题是当我将它们分别编译为 main.o 和 server.o 并在以下 makefile 中为程序链接它们时:

生成文件

CC = g++
#C++ Version Number
VERSION = 2a
# compiler flags:
#  -g    - this flag adds debugging information to the executable file
#  -Wall  - this flag is used to turn on most compiler warnings
CXXFLAGS  = -std=c++$(VERSION) -g -Wall
LFLAGS    = -std=c++$(VERSION) -g -Wall -c
# Libraries
INC = $(shell pwd)/external_libraries/include/
LIB = $(shell pwd)/external_libraries/lib/
FLAGS = -lboost_coroutine -lboost_context -lboost_chrono -lcrypto -lssl -lboost_system -pthread -fcoroutines -lcassandra

main : main.o server.o cassandra/cql.o
    $(CC) $(CXXFLAGS) main.o server.o cassandra/cql.o $(foreach inc,$(INC), -I$(inc)) $(foreach lib,$(LIB), -L$(lib)) $(FLAGS) -o main

main.o : ssl/server_certificate.hpp server.hpp main.cpp
    $(info Compiling Main.cpp)
    $(CC) $(LFLAGS) main.cpp $(foreach inc,$(INC), -I$(inc)) $(foreach lib,$(LIB), -L$(lib)) $(FLAGS) -o main.o


server.o : server_config.hpp server.hpp server.cpp
    $(info Compiling Server.cpp)
    $(CC) $(LFLAGS) server.cpp $(foreach inc,$(INC), -I$(inc)) $(foreach lib,$(LIB), -L$(lib)) $(FLAGS) -o server.o

我收到重复的错误,例如:

...
/opt/rh/gcc-toolset-11/root/usr/bin/ld: server.o: in function `boost::urls::parse(char const*&, char const*, boost::system::error_code&, boost::urls::userinfo_bnf&)':
/home/warrenniles/Desktop/project/webserver/external_libraries/include/boost/url/rfc/impl/userinfo_bnf.ipp:28: multiple definition of `boost::urls::parse(char const*&, char const*, boost::system::error_code&, boost::urls::userinfo_bnf&)'; main.o:/home/warrenniles/Desktop/project/webserver/external_libraries/include/boost/url/rfc/impl/userinfo_bnf.ipp:28: first defined here
...
collect2: error: ld returned 1 exit status

或全部以以下形式:

/opt/rh/gcc-toolset-11/root/usr/bin/ld: server.o: in function `boost::urls::<function_def>:
/home/warrenniles/Desktop/project/webserver/external_libraries/include/boost/url/rfc/impl/userinfo_bnf.ipp:<some_number>: multiple definition of `boost::urls::<function_def>'; main.o:/home/warrenniles/Desktop/project/webserver/external_libraries/include/boost/url/rfc/impl/userinfo_bnf.ipp:<some_number>: first defined here

我想保留它,以便我编译服务器.cpp,然后编译main.cpp,最后将它们链接在一起,但是我是提升和制作的新手,不知道如何解决这个问题。

C++ Boost 生成文件 链接器错误

评论


答:

1赞 user7860670 12/8/2022 #1

如果您尝试在仅标题模式下使用它,则必须包含在一个翻译单元中。它是将其链接为动态或静态库的替代方法。对于声明,应包含其他标头,例如boost/url/src.hpp#include <boost/url/url.hpp>