R
R
rhaport2016-05-24 00:58:17
C++ / C#
rhaport, 2016-05-24 00:58:17

What is the correct way to use extern "C"?

The project uses C and C++ objects. For linking to work, it is necessary to encapsulate C function declarations in extern "C" {...}.
I usually do this in the header of the C module

// my_c_header.h
#ifdef __cplusplus
extern "C" {
#endif

void spam(void);

#ifdef __cplusplus
}
#endif

and calmly include the C header in the C++ file.
However, in the project I encounter constructions of the type
// my_cpp_header.hpp

extern "C" {
#include "my_c_header.h"
}
...

At the same time, nothing additional is written in my_c_header.h itself.
It looks unsafe to me, since my_c_header.h could be included somewhere earlier without extern "C" around, then including above would be ineffective. Well, in general, the widespread use of extern "C" {} around #include looks heavy.
What do you think about this? How do you mix C and C++ in your projects?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
OnYourLips, 2016-05-24
@rhaport

However, in the project I encounter constructions of the type
It is right. These parts of the project are written in C and are meant to be used in C.
Why would C code check for a predefined preprocessor constant from another language?
And if it will be used from a dozen other languages, then you will put ten such checks into C code?

#
#algooptimize #bottize, 2016-05-24
@user004

How many people write code?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question