Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MSBuild to compile a single cpp file

I can build the whole project by calling MSBuild from the command line:

C:\MyProject>MSBuild MyProject.vcproj

However I didn't find any information about compiling a single file. In essence I would like to do something like

C:\MyProject>MSBuild MyProject.vcproj /t:Compile:MySourceFile.cpp

I do not want to directly use 'cl.exe' from the command line since that would force me to define all relevant command line options for cl.exe and all the environment variables, a task which MSBuild is already doing for me.

Is there any way to achieve that?

And please, do not suggest using 'make' or 'ant' or whatever, I specifically need MSBuild. Thanks

like image 384
Yariv Avatar asked Nov 13 '10 12:11

Yariv


2 Answers

MSBuild in VS2008 uses VCBuild to do the actual work, and VCBuild has no option I know of to build a single file. (with VS2010 this has changed, there you can actually invoke a compile of a single file using something like "/t:ClCompile "p:/SelectedFiles="main.cpp")

I can come up with some ideas that will certainly work, but require some extra work and are not very straightforward:

  • you can msbuild have invoke devenv to compile a single file:

    devenv myproject.sln /Command "File.OpenFile myfile.cpp" /Command "Build.Compile" /Command "File.Exit"
    

    this does open the IDE window though, and will make it pretty hard to figure out if the compile actually succeeded or not.

  • have msbuild invoke a script/program which parses the vcproj and makes a copy with all sources under the Source File section removed except that one file you want to compile. Then have msbuild build that project using vcbuild /pass1 (pass1=compile only, no link).

  • always keep a response file having the same options as your vcproj and let msbuild invoke cl to compile the single file, using the response file. (making the response file is as simple as opening the project properties in VS, going to C++->CommandLine and copying everything listed)

like image 172
stijn Avatar answered Sep 20 '22 00:09

stijn


You can do it like this (which is how VS invokes MSBuild when you Ctrl+F7 on a file):

msbuild MyProject.vcxproj /t:ClCompile /p:SelectedFiles=MySourceFile.cpp

Note that the SelectedFiles property needs to match the <ClCompile> item in the .vcxproj, so it may be something more like ..\path\to\MySourceFile.cpp, depending on how your files are organized.

like image 45
Mike Fitzgerald Avatar answered Sep 20 '22 00:09

Mike Fitzgerald