views:

2945

answers:

1

**C newbie alert** How do I compile a C app so that it runs without showing a console window on Windows? I'm using Windows XP and GCC 3.4.5 (mingw-vista special r3). I've googled this exhaustively and I've come up with the following which, according to what I've read, sounds like it's supposed to do the trick, but doesn't on my system:

#include <windows.h>
#include <stdlib.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    system("start notepad.exe");
}

I've also tried passing the "-mwindows" argument to GCC to no avail. The code sample launches Notepad but still flashes up a command prompt.

EDIT: FWIW I have also tried ShellExecute as an alernative to system(), although I would be happy to even get an app with an empty main() or WinMain() working at this point.

+8  A: 

Retain the -mwindows flag and use this:

#include <windows.h>
#include <process.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    execl("c:\\winnt\\system32\\notepad.exe", 0);
    // or: execlp("notepad.exe", 0);
}

Note: you need the full path for the execl() call but not the execlp() one.

Edit: a brief explanation of why this works - using system() starts a shell (like cmd.exe) to exec the command which produces a console window. Using execl doesn't.

anon
Perfect! Thank you.
Wayne Koorts
Ah, thanks for the edit too - I figured it was something like that. (Where's the +2 button? ;-)
Wayne Koorts
You shouldn't need the full path if you use execlp().
paxdiablo
Pax: Thanks, that's even closer to what I was needing :)
Wayne Koorts
@Neil, added that to the text, hope you don't mind.
paxdiablo