Can you make a VC++ Solution set preprocessor #def

2019-02-17 20:22发布

问题:

I have a library which supports a #define to control how it's built. However the library can be used by multiple EXE projects which want different versions. Can I make the app/EXE project set the #define to be used by the library when built, or set it in the solution?

The only other option I can think of is creating a separate build-configuration on the library project but that would quickly get out of control. That's common for e.g unicode/non-unicode builds but then you'd end up multiplying the number of configurations for every combination.

回答1:

The following approach assumes that every .EXE/app (which uses this library) has its own Visual Studio Solution.

You do have control over the library, right? Steps 1-3 will make changes to its project file, and step 4 adds a file to the library source code.

  1. Set Project Properties > C/C++ > Advanced > Force Includes to mylibrary_solution_defines.h .

  2. Edit Project Properties > C/C++ > General > Additional Include Directories to put $(SolutionDir); at the beginning of the list of directories.

  3. Set both Project Properties > General > Output Directory and Intermediate Directory to something relative to the solution directory. Perhaps $(SolutionDir)$(ProjectName)\$(Configuration)? You want to make sure the library gets rebuilt for every solution that uses it; there shouldn't be any sharing of .lib or .obj files.

  4. Create an empty, dummy header file called mylibrary_solution_defines.h and put it in your library source code so a #include "mylibrary_solution_defines.h" will never fail.

  5. In every app/EXE solution -- assuming you have different solutions for each app that uses this library, otherwise this whole plan will fail -- create a mylibrary_solution_defines.h file with your #defines in it.

Do you see what's happening? Every library source file implicitly #includes "mylibrary_solution_defines.h", and it preferentially gets that file from the solution directory. So that file can be different for every solution. So if your solution ConsoleModeInterfaceProgram.sln needs the library built with #define TEXTONLY 1, put that line into the mylibrary_solution_defines.h that's in the same directory as ConsoleModeInterfaceProgram.sln.



回答2:

You'll need separate build configurations for each library version that any of your applications requires. That's how the build system is designed.

The only way out would be to add the source code for the 'library' directly to the respective application projects and set the correct preprocessor settings per-project - this way, you still have the benefit of a shared codebase.