5

Can I declare a function as static and with extern "C" linkage in one line?

E.g, with GCC I can do this:

extern "C" {

  static void MyHandler (void)
  {
     // some code here
  }

}

And it does exactly what I want it to do.

For aesthetic reasons I don't like the extern "C" {} block however.

I can also write:

extern "C" void MyHandler (void) { ...

or

static void MyHandler (void) { ...

but if I combine them neither of the following two seem to work:

extern "C" static void MyHandler (void) {...
static extern "C" void MyHandler (void) {...

Q: Is there a way to combine the two linkage modifiers without using an explicit extern "C" block?

Nils Pipenbrinck
  • 83,631
  • 31
  • 151
  • 221
  • Why `static` if should be used externally? – πάντα ῥεῖ Sep 20 '15 at 12:14
  • 5
    But why would you want anything like that? Marking a function `extern "C"` is useful if you need to export the function outside of the translation unit in an unmangled form, but then making the function `static` as well kind of defeats that purpose, as the function will not be exported. – Some programmer dude Sep 20 '15 at 12:14
  • 1
    @πάνταῥεῖ The function is an interrupt handler in an embedded system. The linker needs this to be extern "C". Otherwise he will not be able to put it into the interrupt vector table. I don't want anyone but the hardware to call this function though, that's why static would be nice as well. – Nils Pipenbrinck Sep 20 '15 at 12:46
  • @JoachimPileborg The function is an interrupt handler in an embedded system. The linker needs this to be extern "C". Otherwise he will not be able to put it into the interrupt vector table. I don't want anyone but the hardware to call this function though, that's why static would be nice as well. – Nils Pipenbrinck Sep 20 '15 at 12:47
  • 1
    The linker won't actually be able to use the function anyway if you declare it as `static`. The linker can only use symbols that are exported from the translation units, and `static` functions are not exported (there might not even be an entry for it in any symbol table of the object file). – Some programmer dude Sep 20 '15 at 12:53
  • 1
    @JoachimPileborg Well, you're right! Much to my surprise after a complete rebuild it works without extern "C" just fine! Thanks. – Nils Pipenbrinck Sep 20 '15 at 13:59

1 Answers1

0

Is there a way to combine the two linkage modifiers without using an explicit extern "C" block?

No. extern implies external linkage where as static implies internal linkage. Both are contradicting and can't be applied on the same definition.

There are multiple good answers that explain this like here and here.

In fact, what's happening even in case of the extern "C" block is that, the static on MyHandler is overriding the extern "C" of the block as its defined in a nested scope. Net effect is that MyHandler is ending up with internal linkage and the extern "C" has no effect.

Dhwani Katagade
  • 939
  • 11
  • 22