Question

The following basic Win32 program compiles just fine in Dev-C++.

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
    MessageBox(NULL,"Hello, world!","My app", MB_OK ) ;
}

But now I'm trying to compile it using Visual Studio 2005. I open the Visual Studio command prompt and type:

cl test.cpp

But I get the following errors:

test.cpp
test.obj : error LNK2019: unresolved external symbol __imp__MessageBoxA@16 referenced in function _WinMain@16
test.exe : fatal error LNK1120: 1 unresolved externals

I thought the problem might be the path for the linker, but according to this MSDN page, the linker looks for it in the enviromental variable LIB which is already set in the Visual Studio prompt to:

C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB;
C:\Program Files\Microsoft Visual Studio 8\VC\LIB;
C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib;
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\lib;

What else is needed to compile a Win32 program in the command line?

I'm using Visual Studio 2005 SP1 update for Vista.

Was it helpful?

Solution

Add user32.lib to the command: it's an import library for user32.dll, which is linked in by default by g++, but not by Visual C++.

In general, just check the documentation of whatever function the linker protests about.


Note that you do not need to use that non-standard Microsoft monstrosity WinMain.

Instead just use standard C++ main.

Then with Microsoft's linker, if you want a GUI subsystem executable add option /entry:mainCRTStartup.


Minimal C++03 example:

#define UNICODE
#include <windows.h>

int main()
{
    MessageBox( 0, L"Hello, world!", L"My app:", MB_SETFOREGROUND );
}

Building from command line with Visual C++ 12.0 as GUI subsystem executable:

[D:\dev\test]
> set cl & set link
CL=/EHsc /GR /FI"iso646.h" /Zc:strictStrings /we4627 /we4927 /wd4351 /W4 /D"_CRT_SECURE_NO_WARNINGS" /nologo
LINK=/entry:mainCRTStartup /nologo

[D:\dev\test]
> cl winhello.cpp /Fe"hello" /link /subsystem:windows user32.lib
winhello.cpp

OTHER TIPS

You need to link the User32 library. Add this just below your includes

#pragma comment(lib,"User32.lib")

#pragma lets you provide additional information to the compiler

#pragma comment (lib, "library.lib") allows the user to pass this comment to the linker to specify additional libraries to link

COMMAND LINE COMPILATION OF A WIN32 APPLICATIO USING C

cl w1.c /subsystem:windows gdi32.dll user32.dll

SET THE FOLLOWING ENVIRONMENT VARIABLES INCLUDE LIB PATH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top