Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a C header file that can be used in C++ programs? [duplicate]

Tags:

c++

c

macros

Possible Duplicate:
How to check (via the preprocessor) if a C source file is being compiled as C++ code

I'm trying to find a standard macro which will test whether a header file is being compiled as C or as C++. The purpose of this is that the header may be included by either C or C++ code, and must behave slightly differently depending on which. Specifically:

In C, I need this to be the code:

extern size_t insert (const char*);

In C++, I need this to be the code:

extern "C" size_t insert (const char*);

Additionally, is there a way to avoid putting #ifdef's around every declaration in the header?

like image 226
Talia Avatar asked Sep 22 '12 23:09

Talia


People also ask

Can you use header files twice in a program?

Note: We can't include the same header file twice in any program.

How do I make a header file in C?

To make a header file, we have to create one file with a name, and extension should be (*. h). In that function there will be no main() function. In that file, we can put some variables, some functions etc.

What happens if we include a header file twice in C?

If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time. This construct is commonly known as a wrapper #ifndef.

Which header file is used in C?

In C language, header files contain the set of predefined standard library functions. The “#include” preprocessing directive is used to include the header files with “. h” extension in the program.


2 Answers

It is normal to bracket C header files as follows so they can be used in C++ programs. Check your system header files such as stdio.h and you will probably see this:

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif
like image 52
Jim Balter Avatar answered Oct 15 '22 03:10

Jim Balter


The answer is to use the macro __cplusplus. In this instance, the most straightforward approach is:

extern
#ifdef __cplusplus
"C"
#endif
size_t insert (const char*);

This macro is part of the C++ standard.

like image 38
Talia Avatar answered Oct 15 '22 04:10

Talia