reshefm
reshefm

Reputation: 6167

Calling c function in a lib file from c++

I have to call a c function declared in a lib file from c++. What instructions/attributes/configuration I have to set for this?

Upvotes: 2

Views: 1245

Answers (3)

pythonic metaphor
pythonic metaphor

Reputation: 10546

If you're writing the header files yourself, it's often nice to do something like this

 #ifdef __cplusplus
 extern "C" {
 #endif

...

 #ifdef __cplusplus
 }
 #endif

so that this gets ignored by your c compiler, but picked up by c++ one. Incidentally, for a good discussion of why you need this, check out

Why do we need extern "C"{ #include <foo.h> } in C++?

Upvotes: 1

AlastairG
AlastairG

Reputation: 4314

Do you have a header file for the library? If so it should have

extern "C" {
blah blah
}

stuff in it to allow it to be used by C programs. If not, then you can put that around the include statement for the header in your own code. E.g.

extern "C" {
    #include "imported_c_library.h"
}

Upvotes: 5

CashCow
CashCow

Reputation: 31435

ensure you put extern "C" before the declaration of the function if it isn't already in the header.

Upvotes: 2

Related Questions