Evgenii B. Rudnyi, 2006-2008, (c) All rights reserved
The goal of this text is to compare the compilation process between Visual
C++ and gcc (see Compiling and Linking: Simple
Example with gcc). The process is quite similar but behavior of the tools
in Visual Studio is a bit different. The librarian in Visual Studio is
link and the compiler is cl.
The sample code is in example.tar.gz or you can browse it here.
If you have already unpacked the archive by running the example with gcc, please skip this step.
It is assumed that the archive is already in the current directory.
$ tar zxvf example.tar.gz
The command creates directory example/lib with files
testlib.cpp and testlib.h and directory
example/app with file main.cpp. The goal is first
to compile and make the library and then link the application with the
library.
$ cd example/lib
$ cl -EHsc -c testlib.cpp
$ lib -out:testlib.lib testlib.obj
The flag -c forces cl to compile to the object
file without linking. Note that the extension of the object file is
.obj (not .o as on Unix). The flag
-EHsc is necessary to specify the exception model. Without it
cl writes a lot of warnings when one uses the C++ Standard
Library.
The librarian makes a library from the object files. The extension for the
library is .lib (not .a as on Unix).
$ cd ../app
$ cl -EHsc -c -I../lib main.cpp
File main.cpp contains a pragma #include that
requires cl to find the header testlib.h. In our
case, cl does not know where the header is and we must use
-I to tell it. The command is very similar to that of
gcc. The difference is again in the extension of the object
file, .obj and not .o.
Now we want to convert the object file main.obj to the
executable. Along this way, it is necessary to link it with the library
testlib.lib. The right command is as follows:
$ cl main.obj testlib.lib -link -LIBPATH:../lib
The library is written along with the object file. The way to specify the
location of the library is completely different as compared with gcc. Instead
of -L it is -LIBPATH: and additionally it is a part
of option for the linker that should be specified by -link.
It is possible not to specify the file name for the binary. By default it
is the name of the first object file with the extension
.exe. However if one needs to specify it, this
should go as a part of the linker options after -link
-out:main.exe.
$ ./main.exe
By default VC++ turns safe iterators on and loose performance:
Numerics: Visual C++ vs. g++
optimization in VC++ Express Edition 2005 Options
Please post your comments, questions, suggestions to the discussion group at http://groups.google.com/group/matrixprogramming.