Sometimes you want to have a library of your functions within one object file that you can use for other applications without having to re-compile and import each time to each project.
Well, if you create a object of the list of functions because a object file is the intermediate between code and linking (to create the executable file), but with this object file you will need to have created a header file (.h) that will allow the projects to know what functions are within the object file and how to call them. So to start with here is the header file (I have called it libraryHelloWorld.h)
#include <iostream> using namespace std; void SayHelloWorld(); void SayWord(std::string st); |
It just defines the two functions that I have written, and here are the implementation of the two functions above.
#include "libraryHelloWorld.h" #include <iostream> using namespace std; void SayHelloWorld() { cout << "Hello World" << endl; } void SayWord(string st) { cout << "Line is \"" << st << "\"" << endl; } |
if you save that as libraryHelloWorld.cpp, if you notice that at the top I am including the header file to this cpp file because the header files normally have a class definition inside them and also struct’s etc, which the functions within the cpp file may require.
To compile up, to create the object file you just need to do
g++ libraryHelloWorld.cpp -c |
which basically means (-c) just compile and do not link, this will create a libraryHelloWorld.o file (the object file).
To make use of this object file, you just need to add in the header file to your project and then call the functions as though you have re-written them within your new project, like so.
#include "libraryHelloWorld.h" int main() { SayHelloWorld(); SayWord("Genux is great"); return 0; } |
Then the main part, which is including the object file created before into the linking part of the computation of this program. (save the above as callHelloWorld.cpp)
g++ callHelloWorld.cpp libraryHelloWorld.o -o callHelloWorld |
the above includes the object file, libraryHelloWorld and after the linking part of the compilers job, the output file name (-o) will be callHelloWorld.
This just saves allot of time when you are coding, try to keep different projects having similar libraries that you know and trust to work.