Skip to content

Dynamic Linking and Static Linking in Linux Cmake

Dynamic Linking

In dynamic linking, the C++ runtime libraries are separate shared objects (.so files) that your program depends on at runtime. These shared libraries are loaded dynamically when your program runs.

To use dynamic linking with CMake, follow these steps:

  • First, build the shared library (.so) containing the functions you want to use. You can create this library as part of your CMake project.
  • In your CMakeLists.txt, add the following lines to create and link the shared library:
  add_library(power SHARED power_sources.cpp power.h)
  target_include_directories(power PUBLIC ${PROJECT_BINARY_DIR} ${PROJECT_SOURCE_DIR})
  • The generate_export_header function generates macros for exporting functions on shared library interfaces in a portable way.
  • Next, link your executable to this shared library:
  add_executable(test main.cpp)
  target_link_libraries(test PRIVATE power)
  • Make sure that the functions you want to use are properly exported from the shared library.

Static Linking

When you statically link the C++ runtime libraries, the necessary code is directly embedded into your executable binary. This means that your program doesn’t rely on external shared libraries at runtime.

To achieve static linking, you need to use the appropriate flags during compilation. In CMake, you can set the compiler flags for static linking using the CMAKE_CXX_FLAGS variable.

  • For example, to compile with the multi-threaded statically-linked runtime library (equivalent to -MT), add the following line to your CMakeLists.txt:
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++")
  • This ensures that your executable contains all the necessary code from the C++ standard library.

Remember that dynamic linking allows you to update shared libraries independently without recompiling your entire program. Choose the approach that best suits your project’s requirements!

For more details, you can refer to the CMake documentation and explore additional options for fine-tuning your linking behavior.

Leave a Reply