Search code examples
c++cmakecompilation

C++ - Why is a Static Library unusable without source files?


So from what I understand, a static compiled mylib.a file should just be usable as plug-and-play. But I can't use it without the source code, I'm trying to avoid that.

I adapted this tutorial to compile using CMake with the following directory structure:

/
   lib
      libmy_math.a
   main.cpp
   my_math.h
   my_math.cpp
   CMakeLists.txt

The contents of the files are exactly as in the tutorial. The only added file is CMakeLists.txt which basically just runs the library compiling part before building:

CMakeLists.txt

cmake_minimum_required(VERSION 3.21)
project(Test)

### Uncomment this ONCE to compile a libmy_math.a file
# add_library(my_math STATIC my_math.cpp)

add_executable(Test main.cpp)

find_library(MY_MATH_LIB my_math HINTS ./lib)
target_link_libraries(Test PUBLIC ${MY_MATH_LIB})

As the CMake file says, uncommenting Line 5 compiles the library, which is then linked to my code when compiling.

I'm trying to package my code so that I don't show my client the source code for the compiled library (my_math), but if I delete the my_math.h and my_math.cpp files, I get a "file not found" error on import:

/Users/Joe/Desktop/Test/main.cpp:1:10: fatal error: 'my_math.h' file not found
#include "my_math.h"
         ^~~~~~~~~~~


I thought you could compile libraries without needing the source code. What am I missing here?


Solution

  • A static library does not contain each and every definition a header can contain - think of macros, etc. Thus you still need the header. However, you don't need the .cpp anymore to link the library.