Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-extern function with C linkage

Tags:

c++

c

linkage

Is it possible to declare a function with C linkage without it having external linkage? When trying to compile

extern "C" static void f() {}

I get

f.cc:1: error: invalid use of 'static' in linkage specification

which makes sense, in a way. In namespace { extern "C" void f() {} }, the extern specifier seems to override the anonymous namespace's restricted scope.

If this is not possible, does it matter when passing a function pointer to C?

like image 874
Fred Foo Avatar asked Jun 10 '11 23:06

Fred Foo


1 Answers

You can do

extern "C" {
  static void f() {}
}

This will give the function f's type C linkage which in practice means that it uses the C calling convention on your platform. The function's name will still have C++/internal linkage, because a language linkage specification only applies to function names of external linkage.

If you specify the extern "C" directly on the declaration, the Standard specifies that the extern "C" is taken to be also a storage class specifier, so if you would add static, then you would get a conflict.

Does it matter when passing a function pointer to C

It can theoretically matter - an implementation is allowed to differ in behavior from calling a function whose type has C++ linkage to calling a function whose type has C linkage. I don't know of implementation details though, just what the spec says about it. Best to follow the spec and you are safe.

like image 178
Johannes Schaub - litb Avatar answered Oct 07 '22 10:10

Johannes Schaub - litb