Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include libraries when compiling with Visual Studio on command line?

I'm attempting to build a program with Visual Studio 2008 on the command line. After reading Walkthrough: Compiling a Native C++ Program on the Command Line. I tried the following:

Run the vcvaralls.bat to setup the enviroment:

"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"

Wrote this simple C++ application:

#define _WIN32_WINNT 0x501
#include <windows.h>
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
    MessageBoxA(0,"Hello","Hello",MB_OK);

    return 0;
}`

And attempted to compile it:

cl /EHsc /GA simple.cpp

And this happens:

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

Which leads me to believe that I need to include user32.lib or similar. I cant figure out from the visual studio manuals how to do that.

like image 505
Zv_oDD Avatar asked Feb 21 '14 07:02

Zv_oDD


People also ask

How will you include a library in C++?

Right-click on the application project node in Solution Explorer and then choose Properties. In the VC++ Directories property page, add the path to the directory that contains the LIB file to Library Paths. Then, add the path to the library header file(s) to Include Directories.


2 Answers

Yes, to use MessageBox you need to link at least with User32.lib, as shown here . Use:

cl /EHsc /GA /MT simple.cpp User32.lib

/MT chooses the Run-time library. In this example I used multi-threaded static library.

like image 95
Bart Avatar answered Nov 14 '22 22:11

Bart


You're correct, MessagBoxA is defined in User32.lib and you need to link your code with it. You can provide the linker options to the CL compiler and it will pass it to the linker. All you need to do is to add the User32.lib to your compilation string: cl /EHsc /GA simple.cpp User32.lib

like image 24
SomeWittyUsername Avatar answered Nov 14 '22 20:11

SomeWittyUsername