Reputation: 325
I was trying to follow along with the C++ headers tutorial here, and as the tutorial says I have the files main.cpp, add.cpp, and add.h. The only is that up until now I haven't been using an IDE and compiling straight from the command line.
But I can't seem to figure out how I would compile add.h and and add.cpp into a library.
As of now, if give the command: g++ -o main main.cpp add.h add.cpp
, it compiles just fine and gives me a main.exe
. But how would I make it so the library (containing add.h and add.cpp) would be precompiled, and saved as a dll? Is this something that's relatively straight forward with the command line?
Thanks for any help guys, cheers.
Upvotes: 4
Views: 7185
Reputation: 1020
There are two types of libraries: static and dynamic libraries. Static libraries are linked together with the resulting program, so each program that uses that library will get its own copy of the library code.
A more memory-efficient way is to use shared libraries (on windows called DLL), which are loaded on demand from a location that is specific for each platform, but the advantage is that only one instance of the library code needs to be loaded to memory when different programs that use the library are running simultaneously, and the resulting binary code of those programs do not contain the library code. it resides in a separate file that needs to be shipped together with the application and installed to a proper location.
If you use unix-like build tools (even on a windows system), this could be a typical sequence of commands you would use to produce a library that contains the code in your add.cpp file:
for a static library:
g++ -c add.cpp
ar crf libadd.a add.o
g++ -o main main.cpp -L. -ladd
the first will compile the add.cpp into add.o, the second will create a static library libadd.a from add.o file. If you want to include more object files into your library, add them to the end of that command line. The last command compiles your main.cpp program while linking it with the static library file libadd.a. The -L. option instructs the linker to search for the library file in the current directory. Alternately, you may want to put the library file in some other directory and use the -Lyour_directory option.
for a shared library (a dll):
g++ -shared -o libadd.so add.cpp
g++ -o main main.cpp -L. -ladd
but to run it, the system must be able to locate the shared library. You can help it by adding the directory where your library is located by adding it to the LD_LIBRARY_PATH environment variable, for instance:
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
for the Windows platform, you may need to use a few more qualifiers, which are nicely explained in the mingw tutorial: http://www.mingw.org/wiki/sampledll
Upvotes: 6