I encountered a strange problem recently. I had a C++ file which used certain custom system calls. The system calls had a few initialization functions to be performed before their usage. It was obvious that i needed a library for this. I made a static library which performed the initialization functions and which had to be linked with any C (or C++ until recently) file.
If you are not with me, here is an example:
- syscalls.h -> the header file with all the system calls/structures etc . this would of course be in /include or /include/linux directories
- using-syscalls.cpp -> a cpp file using the system calls in syscalls.h
- mylib.c ->the library file which had the necessary system call declarations of the form :
- mylib.h -> a header file consisting of the function declaration used in mylib.c
syscallN(....)and some other initialization functions which need to be frequently called
Now the idea was to have using-syscalls.cpp link to a library created by mylib.c here’s how you can proceed.
- obviously using-syscalls.cpp will have the includes of syscalls.h and mylib.h
- yet when you create a static library say, you may get “implicit declarations……” of your custom system calls
- It is necessary to create the library also with g++. Remember to use g++ only. the c++ compiler is more strict than the c compiler
- so first create the library:
#g++ -Wall -c mylib.c
#ar -cvq libtest.a mylib.o
- now for the linking. in your cpp file you must have an extern “C” declaration despite of all the includes. Surprisingly they do not conflict with the header files.So now in our cpp file we have :
extern "C"{
syscallN(....)
syscallN(....)
.......
}
- once this is done, do the compiling and linking in one command (rather than creating the object file of the cpp first)
#g++ -o progname syscalls.cpp -L. -ltest
There…some Not-so-FAQ!
