0

C++ newbie here. I'm creating a C wrapper around C++ library which expose just foo() function.

wrapper.h

#include "SomeLibrary.h"
#include "SomeAnotherLibrary.h"

#ifdef __cplusplus
extern "C" {
#endif
  void foo();
#ifdef __cplusplus
}
#endif

wrapper.cpp

#include "wrapper.h"

void foo() {
  // calls to `SomeLibrary.h` and `SomeAnotherLibrary.h` functions...
}

I would like to compile this code just to be able to call foo() from a different C code. Note that I care just about the foo() function. I would like to completely ignore SomeLibrary.h and SomeAnotherLibrary.h header files.

So I tried to compilethe wrapper into object file wrapper.o as follows:

g++ -c wrapper.cpp -o wrapper.o -I../some_library/include -I../some_other_library/include -L../some_library/lib -lSomeFirstLibrary -lSomeSecondLibrary

Problem:

When I used wrapper.o in my C project, it still require me to load bunch of header files from SomeLibrary.h and SomeAnotherLibrary.h (which I do not care about at all). Here is my C project code:

my_project.c:

#include "wrapper.h"

void main() {
  foo();
}

And compile it:

gcc my_project.c wrapper.o -o my_project

Which yields following error:

my_program.c:3:28: fatal error: SomeLibrary.h: No such file or directory

Question:

How I should compile the wrapper to ignore all other header files except wrapper.h?

user1518183
  • 4,651
  • 5
  • 28
  • 39

2 Answers2

3

Remove

#include "SomeLibrary.h"
#include "SomeAnotherLibrary.h"

from wrapper.h and put those lines in wrapper.cpp next to #include "wrapper.h".

Then remove the -L../some_library/lib -lSomeFirstLibrary -lSomeSecondLibrary linker related flags from the

g++ -c wrapper.cpp -o wrapper.o -I../some_library/include -I../some_other_library/include 

command (-c means no linking is done here so there's no point in passing linker flags)

and move it to the

gcc my_project.c wrapper.o -o my_project -L../some_library/lib -lSomeFirstLibrary -lSomeSecondLibrary

command like this.

Then it should work.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • It removed the missing header error. However, now I get many `undefined reference to` messages. – user1518183 Jun 30 '18 at 17:37
  • That's progress though cuz now things compile and the error's now in the linker. Adding `-L../some_library/lib -lSomeFirstLibrary -lSomeSecondLibrary ` should fix the problem (these also shouldn't need to be in the `g++ -c wrapper.cpp ...` command as that one doesn't do any linking). – Petr Skocik Jun 30 '18 at 17:45
  • @user1518183 Nemáš za co. – Petr Skocik Jun 30 '18 at 18:01
1

When you get undefined reference to... messages, it means that you are declaring functions, and calling them, but never defining them. The error is coming from the fact that you are linking your libraries in the wrong place. You do not need to link libraries to the .o file, you need to link them to the executable file.

OrdoFlammae
  • 721
  • 4
  • 13