Ld: duplicate character

I have a rand.cpp and rand.hpp file and a rand_unif () function. I included the rand.hpp file in the sim_engine.hpp file.

In the main.cpp file, I included the sim_engine.hpp file. If I run makefile, I got this error

ld: duplicate symbol rand_unif() in sim_engine.o and main.o for architecture x86_64 collect2: ld returned 1 exit status 

sim_engine.hpp is the only place rand.hpp comes in. main.cpp does not include rand.hpp, but sim_engine.hpp.

I do not understand why I get a duplicate character error.

 #mod_simu.make project makefile mod_simu : main.o rand.o graph.o street.o isection.o vehicle.o event.o FEL.o sim_engine.o clock.o g++ -o mod_simu main.o rand.o graph.o street.o isection.o vehicle.o event.o FEL.o sim_engine.o clock.o main.o : main.cpp g++ -c main.cpp rand.o : rand.cpp g++ -c rand.cpp graph.o : graph.cpp graph.hpp street.hpp isection.hpp g++ -c graph.cpp street.o : street.cpp street.hpp g++ -c street.cpp isection.o : isection.cpp isection.hpp street.hpp g++ -c isection.cpp vehicle.o : vehicle.cpp vehicle.hpp g++ -c vehicle.cpp event.o : event.cpp event.hpp g++ -c event.cpp FEL.o : FEL.cpp FEL.hpp g++ -c FEL.cpp sim_engine.o : sim_engine.cpp sim_engine.hpp g++ -c sim_engine.cpp clock.o : clock.cpp clock.hpp g++ -c clock.cpp clean: rm *.o mod_simu #end 

This is the makefile that I have.

+4
source share
2 answers

Obviously, you have defined rand_unif several times in your program. You probably only define it once in the text code, but by including the header, this code will compile into multiple .o files.

You probably defined rand_unif in the rand.hpp file. This header is part of sim_engine.hpp, so any .cpp file that includes sim_engine.hpp will automatically get a copy of rand_unif . Apparently both main.cpp and sim_engine.cpp include sim_engine.hpp, so both of these .o files get a copy of the function. C ++ forbids having multiple definitions of the same function, but does not require compliance with this requirement. (He named the rule with one definition.) Linker caught you.

There are two typical solutions to the problem:

  • Move function definition to .cpp file; rand.cpp seems like a good candidate. Make sure rand.hpp contains only the declaration and not the definition.

  • Change the definition in the header file to be embedded. C ++ makes an exception to the unified definition rule for inline functions. Add inline before the declaration in rand.hpp.

+6
source

I assume that you include the function declaration twice in your code. You can try to wrap all inclusions of rand.hpp as follows:

#ifndef RAND_HPP
#define RAND_HPP
#include {file path}
#endif

-one
source

Source: https://habr.com/ru/post/1396697/


All Articles