oaimac
oaimac

Reputation: 626

discard symbol of a .lib file if already exist in Windows with Visual C++

Is it possible to discard already existing symbols of a .lib file when linking with a source code ?

For example, I have a .lib file which is compiled with several source file and a source1.cpp file containing a function : void function1 ().
I have a project containing several file, and one of his file is the same source1.cpp (so contains also the same functions) but which has been modified.
So is it possible to link the lib file to my project in order to take into account the source file and functions of my project instead of those of the .lib file ?

I would like to do that with Visual C++.
At the moment, when doing that I get the common error symbol already defined...

Thanks for your help

Upvotes: 0

Views: 295

Answers (2)

Hans Passant
Hans Passant

Reputation: 942247

This should not happen, an .obj in a .lib is only pulled in when it is needed. Try writing strcpy() in your code for example, no link error even though it is also present in the CRT lib.

Do make sure that you don't need some of the functions in the source1.obj that's stored in the .lib. You diagnose this by using the /verbose linker option. Project + Properties, Linker, Command Line, Additional options box. It shows you what symbols get pulled from the .lib, search for source1.obj. Once it gets used, you do get the linker error if there's a name collision. This is of course error prone and best avoided.

Upvotes: 1

Adrian McCarthy
Adrian McCarthy

Reputation: 48019

No. You should make the symbols distinct. That is, function1 in your project source1.cpp should have a different name than the one in your library.

Without knowing more about the situation, you might want to accomplish this by putting either the library or the project into a namespace.

// lib/source1.h
namespace mylib {
  void function1();
}

// lib/source1.cpp
namespace mylib {
  void function1() {
    ...
  }
}

// project/source1.h
namespace myproj {
  void function1();
}

// project/source1.cpp
namespace myproj {
  void function1() {
    ...
  }
}

Now in your code you can call myproj::function1() or mylib::function1(). Those symbols will be distinct. If you always use one and not the other, the linker will probably discard the one that's not used (at least in an optimized build).

If you don't want to change all the calls in your code, you can add a line like using myproj::function1(), which will tell the compiler that when you say function1() you mean the one from your project.

Upvotes: 0

Related Questions