0

Suppose I have a C++ library lib.h that uses classes and templates. Suppose also that I have a custom C++ header myLink.h with the following:

#include "lib.h"

  //call methods from lib.h that use templates and classes
  //  and return an integer based off of the information gained from calling functions lib.h  
  extern "C" int foo(int param1, const int param2);

Now suppose I am in a C file called test.c. Is it legal to call function foo() as follows?

//in test.c
int first = foo(5, 6);

Also, what is going on at the object code / linker phase of compilation?

Thanks!

CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
  • 2
    You may want to make your "myLink.h" capable of compiling from both C and C++, e.g. by using `#ifdef __cplusplus` to wrap `extern "C" {` and `}` on separate lines. That way the `int foo(int param1, const int param2);` part would be visible to plain C code, and the rest would be visible to C++. Without this, your "test.c" would need a separate way to declare the function. – Kevin Grant Jul 10 '12 at 03:19

1 Answers1

0

Is it legal to call function foo() as follows?

 int first = foo(5, 6);

Yes, it's legal. Although you should read below to make sure this legal call will link.

what is going on at the object code / linker phase of compilation?

The use of classes won't interfere. C++ classes will be compiled to object code that the linker will understand.

Edit from Chris Dodd's comment:

Your templates will also be created by virtue of foo calling them.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • Not really true -- if `foo` uses any templates, they'll be instantiated when you compile the C++ source file that defines `foo`. – Chris Dodd Jul 10 '12 at 03:19
  • You probably need to link with a C++-aware linker. The C++ side may have code that accesses static objects, uses exception handling, or any number of other things that require C++-specific initialization code. – sfstewman Jul 10 '12 at 04:01