I frequently come across C header files that contain extern "C" guards,
but don't contain any actual functions. For example:
/* b_ptrdiff.h - base type ptrdiff_t definition header */
#ifndef __INCb_ptrdiff_th
#define __INCb_ptrdiff_th
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _PTRDIFF_T
#define _PTRDIFF_T
typedef long ptrdiff_t;
#endif /* _PTRDIFF_T */
#ifdef __cplusplus
}
#endif
#endif /* __INCb_ptrdiff_th */
I know that extern "C" prevents name mangling on functions, but does it also prevent against other interfacing issues on variable and type declarations?
Is the use of extern "C" in the example above meaningless in terms of resulting compatibility?
Some compilers (it's rare) implement name mangling for variables too, not just for functions. In that case, extern "C" may be needed.
Some compilers (it's also rare, but required by the standard) implement language linkage for function types, not just names, so typedef void f(); and extern "C" { typedef void f(); } declare different types.
Also, some maintainers won't notice the absence of extern "C" if they modify the header to add functions.
I recommend you just include it.
No, extern C is not needed there, but it may be convenient to have it in all headers to make sure it is not forgotten when a new function is added.
Related
I'm writing a C library, which may potentially be useful to people writing C++. It has a header which looks like this:
#ifndef FOO_H_
#define FOO_H_
#include <bar.h>
#include <stdarg.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void foo_func();
#ifdef __cplusplus
}
#endif
#endif
and I was wondering - should I move the extern "C" bit before including the header include directives? Especially seeing how, in practice, some of those headers might themselves have an extern "C"?
NO, in general you shouldn't move it to include the headers.
extern "C" is used to indicate that the functions is using the C calling convention. The declaration has no effect on variables and #defines, so there is no need to include these. If an #include is inside an extern "C" block, this effectively modifies the function declarations inside that header file!
Background: Without the extern "C" declaration, when compiling using a C compiler, a function is assumed to follow the C convention, and when compiling using a C++ compiler, the C++ convention is assumed. In case the same header file is used for C and C++ code, you would get a linker error, since the compiled function has different names in C and C++.
Although it's possible to put all your code between the #ifdef blocks, I personally don't like it, because it's really only intended for the function prototypes, and I frequently see people copy-pasting this at places where it shouldn't be. The cleanest way is to keep it where it's supposed to be, which is around the function prototypes in a C/C++ header file.
So, to answer your question "should I move the extern "C" bit before including the header include directives?", my answer is: No, you shouldn't.
But is it possible? Yes, and in many cases this won't break anything. Sometimes it is even necessary, if the function prototypes in an external header file are incorrect (e.g. when they are C functions and you want to call them from C++) and you cannot change that library.
However, there are also cases where doing so breaks the build. Here's a simple example that fails to compile if you wrap the include using extern "C":
foo.h:
#pragma once
// UNCOMMENTING THIS BREAKS THE BUILD!
//#ifdef __cplusplus
//extern "C" {
//#endif
#include "bar.h"
bar_status_t foo(void);
//#ifdef __cplusplus
//}
//#endif
foo.c:
#include <stdio.h>
#include "foo.h"
#include "bar.h"
bar_status_t foo(void)
{
printf("In foo. Calling bar wrapper.\n");
return bar_wrapper();
}
bar.h:
#pragma once
typedef enum {
BAR_OK,
BAR_GENERIC_ERROR,
BAR_OUT_OF_BEAR,
// ...
} bar_status_t;
extern "C" bar_status_t bar_wrapper(void);
bar_status_t bar(void);
bar.cpp:
#include <iostream>
#include "bar.h"
extern "C" bar_status_t bar_wrapper(void)
{
std::cout << "In C/C++ wrapper." << std::endl;
return bar();
}
bar_status_t bar(void)
{
std::cout << "In bar. One bear please." << std::endl;
return BAR_OK;
}
main.cpp:
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
#include "bar.h"
int main(void)
{
bar_status_t status1 = foo();
bar_status_t status2 = bar();
return (status1 != BAR_OK) || ((status2 != BAR_OK));
}
When uncommenting the blocks in a.h, I get the following error:
main2.cpp:(.text+0x18): undefined reference to `bar'
collect2.exe: error: ld returned 1 exit status
Makefile:7: recipe for target 'app2' failed
Without, it builds fine. A C main calling only C functions from foo and bar will build fine either way, since it's unaffected by the #ifdef __cplusplus blocks.
Surprisingly yes. After reading the standard now even I would write
#ifndef FOO_H_
#define FOO_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <bar.h>
#include <stdarg.h>
#include <stddef.h>
void foo_func();
#ifdef __cplusplus
}
#endif
#endif
For 2 reasonss:
1 Having nested extern "C" are no problem, so your bar.h include would be fine. Like this it looks clearer and more important
2 To be really portable your surprisingly have to wrap an extern "C" around your C headers for C++ users, if they don't want to.
Because I just looked thru the C++ Standard and 16.5.2.3 Linkage [using.linkage] states
Whether a name from the C standard library declared with external linkage has extern
"C" or extern "C++" linkage is implementation-defined. It is
recommended that an implementation use extern "C++" linkage for this
purpose.1
To be safe than sorry, you indeed should wrap an extern "C" around those includes but, you should not have to, since this implies to the headers in D.9 C headers [depr.c.headers] like <stdlib.h> which you are using.
This is covered in the C++ FAQ.
First, How to include a standard C header file in C++ code? Nothing special is needed, as standard C header files work seamlessly with C++. So you don't need to wrap stdarg.h and stddef.h in extern "C".
Then, for non-standard C headers, there are two possibilities: either you can’t change the header, or you can change the header.
When you can't change the C header, wrap the #include in extern "C".
// This is C++ code
extern "C" {
// Get declaration for f(int i, char c, float x)
#include "my-C-code.h"
}
int main()
{
f(7, 'x', 3.14); // Note: nothing unusual in the call
// ...
}
When you can change the header, edit it to conditionally include extern "C" in the header itself:
#ifdef __cplusplus
extern "C" {
#endif
. . .
#ifdef __cplusplus
}
#endif
In your case it comes down to whether you have control over the contents of bar.h. If it's your header, then you should modify it to include extern "C" and not wrap the #include itself.
Headers should work the same way regardless of how/when/where they are included. Wrapping an #include in extern "C", #pragma pack, special #defines, etc, should be reserved for last resort workarounds, as this may interfere with how the header behaves in different scenarios, reducing the system's maintainability in the long run.
As StoryTeller said in the comments:
Some headers are explicitly written under the assumption that the outermost "scope" has C++ language linkage. They may use __cplusplus to remove template declarations, and if you wrap them up like you wish to, your header will be fundamentally broken. So as mentioned already, make your declarations correct, and let other headers do their thing unimpeded. Even standard library headers may break (since an implementer may reason its going to be shared anyway, and then do some expert friendly things inside).
Note that standard C headers may be implemented using C linkage, but may also be implemented using C++ linkage. In which case wrapping them in extern "C" might result in link errors.
In a file, I have this macro:
#if defined(__cplusplus)
#define EXTERN_C extern "C"
#else
#define EXTERN_C extern
#endif
But searching on the web, it doesn't seem typical for such macros to have an extern on the C path (though some examples exist). They generally come in pairs more akin to EXTERN_C_BEGIN and EXTERN_C_END to wrap up a group of declarations...and are a no-op in C builds.
But this means in a header file, you wind up having to write:
EXTERN_C_BEGIN
extern int x; /* ...but I already said extern... */
void doSomething(int y);
EXTERN_C_END
This happens because extern "C" int x; is equivalent to extern "C" { extern int x; }... not extern "C" { int x; }. The latter form only gives "C linkage", but not the historical meaning of C extern. Then if you try to make the single-line form decay in C to extern, you can't say EXTERN_C extern int x;, the compiler will complain in the C++ build at the two-externs-on-one-declaration.
Since there's no begin/end form, it's (often) going to mean more typing. But I prefer the "announcement of intent" to the compiler, even in the C case:
EXTERN_C int x;
EXTERN_C void doSomething(int y); /* does `extern` help the C case? */
I cannot offhand seem to create a good scenario where having the extern on the function declarations helps catch a mistake in C. But intuitively it seems there might be value in the redundancy, and as I say, having to do extern "C" and then later still put extern on things feels awkward.
What is the reasoning to prefer (or avoid) either approach?
Usually you see this in headers that were written for C and later made compatible with C++. The easiest way to do that is to simply wrap the whole header in extern "C" { and }. That way there's no need to touch every single declaration, and the main contents can stay plain C.
The macros you're talking about simplify this wrapping. Now it's just two lines:
EXTERN_C_BEGIN
EXTERN_C_END
Instead of the slightly more elaborate dance you'd have to do otherwise to hide the lines from the C compiler:
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
The other issue is that global variables are relatively rare (compared to functions), and you don't need extern in function declarations. So there's less need for an extern macro.
If there are multiple declarations to be marked then your way ends up being more verbose than the begin/end way.
My most preferred form is the one where nothing is hidden -- someone reading the code doesn't have to go and look up what EXTERN_C is defined as in order to understand the code. With your suggestion, the reader would have to go and check whether it was extern or blank in C mode, or even something else.
Your way would work but I think a large part of it is conforming to what others reading the code will expect.
Adding 'extern' to a function declaration in a header file have no real benefits. So, the 'extern' is present in C++ versions of the macro because it is needed to tell the compiler to use C calling-convention for such functions. For a C compiler the extern can be ommited altogether.
See this answer for my details: https://stackoverflow.com/a/856736/1050181
I have these two namespaces, each one containing a function with the same name, like
namespace group1 {
void add(int arg) {
}
}
namespace group2 {
void add(bool arg) {
}
}
and I specify this in the header with the declarations
#ifdef __cplusplus
extern "C" {
#endif
// My namespaces and functions prototypes here
#ifdef __cplusplus
}
#endif
and I am trying to export them into a DLL, with GCC. I get a warning about a conflict between them because they have the same name, then an error at linking time. I thought the name was mangled in the object file based on the arguments, too. I don't know if the linker cares about the namespace too. How could I make this work? Thanks.
If these are C++ functions, you have to remove the extern "C" bracketing:
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
extern "C" tells the compiler "don't mangle this name"--but (as you say) you want the mangling.
You can't really do that directly. When you use the extern "C", you are declaring that the functions are exported as if they were C functions, not C++.
This means (among other things)
Namespaces are removed, and are not considered part of the name
No name mangling due to arguments is done
The best you can do is create extern "C" functions which redirect.
#ifdef __cplusplus
extern "C" {
#endif
void group1_add(int arg);
void group2_add(bool arg);
#ifdef __cplusplus
}
#endif
And the implementations of the wrapper functions would then use either group1::add() or group2::add() as appropriate.
I understand that when you include a c header in your c++ project you must wrap it with extern "C" because c++ and c have two different ways of identifying function. c will use the name to identify a function and c++ must use the name and the parameters to satisfy function overloading.
What I don't understand is why are there are c headers that don't require to be wrapped in extern "C" like windows.h??
In general, wrapping a C header in extern "C" is not a good idea. The header might include other files that break when you do this. A C header that is designed to be used in C++ will handle extern "C" appropriately, without you having to do anything. Typical code:
#ifndef MY_HEADER_INCLUDE_GUARD
#define MY_HEADER_INCLUDE_GUARD
#ifdef __cplusplus
extern "C" {
#endif
/* C callable stuff goes here */
#ifdef __cplusplus
}
#endif
#endif /* MY_HEADER_INCLUDE_GUARD */
I want to use some c++ classes in shared library with C linkage. And i got following problems.
If
#include <iostream>
extern "C"
{
void f(){}
}
Compiles and links succesfully, but f() could not be found in resulting library.
If
extern "C"
{
#include <iostream>
void f(){}
}
I got many compiler errors (just dont know how to correctly translate them in english, something about template with C linkage) on every occurence of C++ keyword "template" in iostream and included headers.
What should be done?
The first variant is correct. Only stuff that even exists in C can be declared in a extern "C" block, and templates and classes certainly don't belong in that category. You only have to make sure, that your function is also declared as extern "C" in the header if you are using a C++-compiler. This is often achieved by writing
#ifdef __cplusplus
// C++ declarations (for example classes or functions that have C++ objects
// as parameters)
extern "C"
{
#endif
// C declarations (for example your function f)
#ifdef __cplusplus
}
#endif
in the header.
The first is correct; system headers (and most other headers as well)
can only be included at global scope, outside any namespaces, classes,
functions or linkage specification blocks. There are likely things in
<iostream> that wouldn't be legal in an extern "C", and even if
there weren't, the name mangling for extern "C" is almost certainly
different from that of C++, and the library itself was surely compiled
as extern "C++".
How did you define f? This could be a similar problem: if the source
file compiles it as an extern "C++" function, then the name will be
mangled differently than it was in the client files which compiled it as
an extern "C" function.
The general policy here is to handle the headers and the function
definitions/declarations in the same way you normally do, except that
you ensure that the header can be included in both C and C++ sources,
e.g.:
#if __cplusplus
extern "C" {
#endif
void f();
// Other `extern "C"` functions...
#if __cplusplus
}
#endif
Then include this header in all files where the function f() is used,
and in the file where it is defined.
Use __declspec to export functions, classes, etc...
Also: http://msdn.microsoft.com/en-us/library/a90k134d(v=vs.80).aspx
And this one is very good: http://www.flounder.com/ultimateheaderfile.htm