Search code examples
c++visual-studioprojects-and-solutions

How to split a C++ project into two in Visual Studio?


Scenario 1

A solution SolA contains only 1 project named PrjA.
PrjA is a Win32 console application, the compilation result is PrjA.exe.

How shall I split the source code files in PrjA into PrjA1 and PrjB, so that the management of the source code is easier, while the compilation result, PrjA1.exe, will be almost the same as PrjA.exe?

For example, I have PrjA :-

  • PrjA has 300 .cpp files.
  • PrjA.exe sizes 400KB.

I hope to split PrjA into 2 projects :-

  • PrjA1 has 200 .cpp files
  • PrjB has 100 .cpp files.
  • PrjA1.exe is also around 400KB.

I'm not sure how to setup PrjB or what will be its compilation result.
Assume PrjB compiles to PrjB.DLL, sized 100KB, I hope PrjA1.exe will somehow embed PrjB.dll inside itself. Thus the size would be 400KB.
I don't want a 300KB PrjA1.exe, which will dynamically link to 100KB PrjB.dll in runtime.

Question: How shall I set PrjB, and how shall I set the link between PrjA1 and PrjB?

Scenario 2

Same as Scenario 1, just this round PrjA's compilation result is a windows DLL, named PrjA.dll, how shall I split PrjA into PrjA1 and PrjB?

The development environment is Visual Studio 2013 under windows 7 64-bits, but the compilation results are 32-bit.


Solution

  • This is how you move existing code into static library. I use VS2015, it should be the same with VS2013, but I can't check that. I start with the following solution structure: Initial solution structure, all code in one project

    First thing to do is to add new project to the solution. File -> Add -> New project -> Win32 Project

    Check Static library and uncheck precompiled header Win32 Application wizard

    Then click Show all files icon in the solution explorer for both projects. This turn filters off and shows project folder as it is. It should look like this: Solution explorer shows files in project folders

    Drag and drop all needed files from one project to another: Project structure after relocation

    Now reference your library. Uncheck Show all files icon to show References. Right click -> Add reference and check your static library project: enter image description here enter image description here

    Last thing to do is to add include directory to the project that uses the library. This is done in project properties. Be sure to check All configurations and All platforms: enter image description here

    That's it. Now when you build your solution, VS builds your static library, builds your main project and links them together. The result should be identical as if everything is in the same project.