Harsh Panchal
Harsh Panchal

Reputation: 53

Is there any way to declare function as extern "C" with g++ flag?

I am referring to this thread, I have the same requirement (wrap the function call) which requires the extern "C" declaration.

In my case this prototype is declared under a separate header file, I don't want to change this header file or the original code file (in which function call is made). But still I want the compiler to see my function as extern "C". So, I am wondering if there is a way to provide this information with g++ flag (e.g. something like "--externc=foobar").

Upvotes: 1

Views: 352

Answers (3)

Dietmar Kühl
Dietmar Kühl

Reputation: 153830

When including C headers you usually need to wrap them with an extern "C" block if they don't have the corresponding wrapper [conditionally on __cplusplus] inside:

extern "C" {
#include <c-header.h>
}

Nesting these blocks is harmless except that it prevents the header to be migrated to C++, i.e., the internal extern "C"-block is preferrable. If the header is a C++ header you'll need to jump theough a forwarding function:

extern "C" void call_as_c() {
    actual_cxx_function();
}

Sinply pretending that the linkage of a symbol is different than it actually is doesn't quite work.

Upvotes: 4

I believe it is not easily possible (to post-declare as extern "C" exactly one function declared in some previous header).

If you have only one such function (and not many of them), I think the easiest solution would be to either change the header, or perhaps declare that function extern "C" before including the header (if the signature and the arguments or result types of that function permit it, e.g. if the relevant types are defined in some other header, etc...).

Alternatively, write some (e.g. in sed or awk) script which would transform the header.

You could also consider customizing GCC with e.g. an extension coded in MELT (a domain specific language to extend GCC) which would change the internal representation of your declaration as you like. I'm not sure it is worth the effort in your case.

Upvotes: 0

cHao
cHao

Reputation: 86504

If you want to change the linkage / calling convention (which is what extern "C" has every right to do), pretty much the only safe answer is to change it where the function is declared -- ie: in the header. Otherwise, you risk the function being defined differently than it's used, and hilarity ensues.

Upvotes: 1

Related Questions