Search code examples
visual-studiocmakestatic-libraries

Create a static library .lib for sources in different folders


The VS2015 solution has the following structure:

vs2015 Solution -

-Project-A (googletest source code)
-Project-B

-Folder-1 (with source and header files)
-Folder-2 (with source and header files in 2 sub-folders)
-Folder-3 (with source and header files)
-src (with source files)
-include (with header files)

-Project-C (unit tests)

I need to build a static library from all the sources in Project-B and link this static library to Project-C. I tried to use CMake just for Project-B, but could not get it to work. Besides, this creates a projectB.sln within the main *.sln.

What's the best way to deal with this, and ensure that this can scale later if I were to add a new project to the main solution? (I'm stuck with this set-up of the code because the previous developer structured it in that way.)


Solution

  • Why not use CMake for the whole project? Assuming your file structure is similar to that shown in your Visual Studio Solution Explorer, it could look something like this:

    Top-level CMakeLists.txt:

    cmake_minimum_required (VERSION 3.16)
    
    # Name your VS solution.
    project(MyProject)
    enable_testing()
    
    # Add the CMake file in the googletest repo
    add_subdirectory(Project-A)
    # Add the CMake file that configures your static library.
    add_subdirectory(Project-B)
    # Add the CMake file that configures your unit tests.
    add_subdirectory(Project-C)
    

    CMakeLists.txt file in Project-B folder:

    # Add the VS project for the static library.
    project(MyLibProj)
    
    add_library(MyLib STATIC)
    
    # Add the public/private sources for the static library.
    target_sources(MyLib 
        PUBLIC
          Folder-1/MyClass1.cpp
          Folder-1/MyClass2.cpp
          ...
          Folder-2/SubFolder1/UtilityClass1.cpp
          Folder-2/SubFolder1/UtilityClass2.cpp
          ...
          Folder-2/SubFolder2/HelperClass1.cpp
          ...
          Folder-3/Circle.cpp
          Folder-3/Square.cpp
        PRIVATE
          src/ImplClass1.cpp
          src/ImplClass2.cpp
          ...
    )
    
    # Add the include directories for the library.
    target_include_directories(MyLib 
        PUBLIC 
          ${CMAKE_CURRENT_LIST_DIR}/Folder-1
          ${CMAKE_CURRENT_LIST_DIR}/Folder-2/SubFolder1
          ${CMAKE_CURRENT_LIST_DIR}/Folder-2/SubFolder2
          ${CMAKE_CURRENT_LIST_DIR}/Folder-3
        PRIVATE
          ${CMAKE_CURRENT_LIST_DIR}/include
    )
    

    CMakeLists.txt file in Project-C folder:

    # Add the VS project for the executable.
    project(MyExeProj)
    
    # Create the test executable, and link the static library to it.
    add_executable(MyTestExe main.cpp)
    target_link_libraries(MyTestExe PRIVATE MyLib)
    
    add_test(NAME MyTest COMMAND MyTestExe)