Is extern “C” only required on the function declaration?

后端 未结 6 1917
执念已碎
执念已碎 2020-12-01 07:48

I wrote a C++ function that I need to call from a C program. To make it callable from C, I specified extern \"C\" on the function declaration.

6条回答
  •  庸人自扰
    2020-12-01 08:16

    The 'extern "C"' should not be required on the function defintion as long as the declaration has it and is already seen in the compilation of the definition. The standard specifically states (7.5/5 Linkage specifications):

    A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.

    However, I generally do put the 'extern "C"' on the definition as well, because it is in fact a function with extern "C" linkage. A lot of people hate when unnecessary, redundant stuff is on declarations (like putting virtual on method overrides), but I'm not one of them.

提交回复
热议问题