Korchkidu
Korchkidu

Reputation: 4946

CMake project compiling fine SHARED libs but not with STATIC libs

I have one working project (P1) with an EXE calling a STATIC lib. It compiles and execute fine on Windows, MAC and Linux.

Now, I have a second project (P2) with an EXE calling a STATIC lib which also calls another STATIC libs. In this case, it works fine on WINDOWS AND MAC but on Linux, I get a lot of reference not found when linking. I checked:

  1. that the libs are there. OK
  2. that the compiler has access to them. OK.
  3. that CMake files from P1 and P2 are similar. OK.
  4. that compiler flags and commands are similar. OK.

I was desperate and I simply switched libs from STATIC to SHARED. And now, it compiles fine on Linux. Basically, I just changed add_library(lib STATIC ...) to add_library(lib SHARED ...) and now everything works fine.

I don't have any clue why this is working in SHARED but not in STATIC.

Thanks for any help. Best regards.

Upvotes: 0

Views: 239

Answers (1)

Johannes S.
Johannes S.

Reputation: 4626

When your static library A depends on another static library B, this dependency is not resolved during creation of A, but when you link your executable against A. Only then the linker needs B to resolve the symbols required by A (depending on your usage of A).

I cannot find any details about this right now, but I strongly assume that Visual Studio (or the combination with CMake) adds those libraries automatically, so it works on Windows. On Linux, you need to explicitly add B to your link libraries in order to successfully link your executable.

When you create a shared library A, all symbols from B are resolved during creation of B (so the linker actually looks up what it needs from B). Therefore, your example works when you switch to shared libraries.

Upvotes: 1

Related Questions