如何从Visual C++/MSBuild解决方案生成CMake文件?
Absolutely! You’re not stuck here—there are built-in tools in Visual Studio that let you generate a proper CMakeLists.txt directly from your existing VC++ projects/solutions, which is perfect for your time crunch and simple codebase. Let me break down exactly how to do this:
Step 1: Use Visual Studio's Built-in Conversion Wizard
First, make sure you’re using Visual Studio 2019 or newer (this feature isn’t available in older versions). Then:
- Open your existing VC++ solution in Visual Studio.
- Right-click on your solution in the Solution Explorer pane.
- Select Convert to CMake Project from the context menu.
- Follow the wizard prompts: it will scan all your project settings—include directories, compiler flags, linked libraries, output targets, and more—and generate a baseline
CMakeLists.txt(plus project-specific CMake scripts if you have multiple projects).
Step 2: Tweak the Generated CMake Script (If Needed)
Since your code is simple, the auto-generated file will likely cover 90% of your needs. But you might want to double-check and add small customizations if needed:
- Add preprocessor definitions: Use
target_compile_definitions(<your-target-name> PRIVATE YOUR_DEFINE=VALUE) - Include additional directories:
target_include_directories(<your-target-name> PRIVATE path/to/your/includes) - Link external libraries:
target_link_libraries(<your-target-name> PRIVATE your-library.lib)
Step 3: Validate the CMake File
Don’t skip this quick check to ensure everything works:
- In Visual Studio, go to File > Open > CMake and select your generated
CMakeLists.txt. Visual Studio will configure the CMake project automatically—if there are any missing settings or errors, it will flag them in the output window. - Alternatively, open a terminal in your project root and run
cmake -S . -B buildto generate build files manually. If this runs without errors, your CMake setup is good to go.
A quick tip: If your solution has multiple projects, the wizard will create a top-level CMakeLists.txt that includes each project’s individual CMake script—this is exactly the structure most people expect for multi-project CMake setups.
内容的提问来源于stack exchange,提问作者Eugene

