Jun 14, 2015

C/C++ Extern and Use of Library Without Header

Every time you use some external library, you need compile your application with the library header, but this is not really necessary, if you know the library function interface, then the "extern" can help!

The "extern" keyword is used to tell the compiler that the variable will be solved later, at linker time, which means the variable is somewhere. This can be used to create a global variable between different files and solve when compiled/linked together, or simply to avoid the use of the header file of a library! this can be useful for missing header files for example.

Let's use the "Creating C/C++ Shared and Static Library" as example and compile the same library using just the "libsumlib.a" file. Edit the "main.cpp" to include the "extern" keyword:

#include <iostream>

extern int Sum(int,int);

using namespace std;

int main(void)
{
 cout <<  Sum(1,2) << endl;

 return 0;
}

And compile:

g++ main.cpp -Lsumlib/lib/static -lsumlib

Note the missing -I include directory, just the static library "libsumlib.a" is used, the binary can run as always:

 ./a.out 
3

That's all! the whole project with scripts to build can be downloaded here.

0 comentários :

Post a Comment