How to avoid conflicts of variables / functions from two libraries in C ++

I have a similar scenario as described below:

I have one header file first.h It has a function:

 char* getName(); 

and the associated cpp first.cpp file with the function definition

 char* getName(){return "first";} 

and the second header file second.h it has a function:

 char* getName(); 

associated cpp second.cpp file with function definition

 char* getName(){return "second";} 

Now there is a main() function:

 #include "first.h" #include "second.h" int main(){ return 0; } 

when I include these .h files, the compiler gives an error in the getName() function because it conflicts.

How to get rid of this problem without changing .h files

+6
source share
2 answers

You can use namespaces when including these header files:

In the cpp file:

 namespace first { #include "first.h" } namespace second { #include "second.h" } 

Then you can use the following functions:

 ... first::getName(); second::getName(); ... 

Edit: Thanks to Jens's comment, this only works if the features are built-in. If the functions are not built-in and you really cannot change the header files, you can create "wrapper" header files for these functions:

File wrapper-first.h:

 namespace first { char* getName(); } 

File wrapper-first.cpp:

 #include "wrapper-first.h" #include "first.h" char* first::getName() { return ::getName(); } 

... and create the same for the second header file. Then you simply include the wrpper support files in the cpp file and use the code as above.

+5
source

It will be hard. Both libraries will contain the getName character. The linker will resolve the getName character using the first library that provides it. This happens no matter what you do with the headers. You are just lucky that the compiler has already complained and gave you a clear error.

The idea of ​​Thomas Barder will hide the problem with the compiler. It will not fix the linker issue. first::getName will still use ::getName from the second library or vice versa.

A necessary solution is to have first::getName in your own library. This library should refer only to the first library. The main executable links against your supporting library and the original second library. The linker no longer has duplicate characters, because it is called twice. When creating the auxiliary library ::getName comes unambiguously from the first library. When creating the main executable file, it definitely comes from the second library.

+3
source

All Articles