Rob D
Rob D

Reputation: 111

Compile C from C++ Windows

I'm looking for a clean or simple way to programmitically compile c program from C++ application on windows.

My creator.exe executable written in C++ should take NAME constant from user and compile result.c with this constant finaly returning to user the compiled result.exe file.

Example:

// result.c
#ifndef NAME
    #define NAME"undefined"
#endif

int main() {
  printf("Welcome %s\n", NAME);
  return 0;
}

On linux it is easy as I can just invoke:

system("gcc result.c -DNAME Bob -o result");

I'm new to windows and maybe there is a cleaner way to perform such compilation then using system command.

Update

I'm very happy to see so many helpful answers:) I've read all of them and decided I will use system function. Now I don't want to set all the environment variables myself as it is strongly discouraged by Microsoft. I would like to use Developer Command Prompt for VS2019 as it has all those variables already correctly set. From Developer Command Prompt I would like to execute msbuild to compile the result.c source code.

Now the problem is I'm not sure whether it is possible to invoke msbuild under Developer Command Prompt from C++?

What I mean by this is something like:

#define DEV_CMD "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\Common7\\Tools\\VsDevCmd.bat"

sprintf_s(cmd, "cmd \/S \/C \"\"%s\"\" && msbuild \/p:DefineConstants=\"DEBUG;NAME=\"%s\"\" ..\\result\\result.vcxproj", DEV_CMD, "Bob");

/* cmd /S /C ""C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\VsDevCmd.bat"" && msbuild /p:DefineConstants="DEBUG;NAME="Bob"" ..\result\result.vcxproj */
system(cmd);

The above of course does not work as && will open Developer Command Prompt in one process and then it will run msbuild in other process.

Upvotes: 0

Views: 144

Answers (1)

Vladimir Nikitin
Vladimir Nikitin

Reputation: 181

On Windows you can use cl.exe instead of gcc. In order to define something you will need to set cl environment variable.

So the following should help:

system("set CL=%CL% /DNAME#\"Bob\"");
system("cl result.c /out:result.exe");

Read MSDN for more options:

https://learn.microsoft.com/en-us/cpp/build/walkthrough-compile-a-c-program-on-the-command-line?view=vs-2019

https://learn.microsoft.com/en-us/cpp/build/reference/cl-environment-variables?view=vs-2019

Upvotes: 1

Related Questions