Jeff Li
Jeff Li

Reputation: 1120

Why c++ source code can call c code without the extern "C"?

Here is a cpp application calling the linux c function. I compiled and run it in linux with g++ 4.7. It works. I am not good at c++. But I heard that you need to declare the 'extern "C"' when you want to call c function from c++ source file. Why this program works ?

#include <unistd.h>
#include <iostream>

using namespace std;

int main(int argc, const char **argv) {
    rmdir("t");
    cout << "Hello" << endl;
    return 0;
}

Upvotes: 2

Views: 411

Answers (1)

ecatmur
ecatmur

Reputation: 157374

The unistd.h header file is written to be compatible with C++. If you look inside it you will find something like:

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
} // extern "C"
#endif

If you're on a platform where unistd.h is not protected in this manner then you would need to use extern "C" around the include.

Upvotes: 5

Related Questions