Gala Gala - 5 months ago 16
Linux Question

Using Linux API headers made for C in C++

Let's consider this piece of code:

#include <iostream>

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

using namespace std;

int main(void) {

char hi[14] = "Hello world!\n";

if (write(1, hi, strlen(hi)) < 0) {

cout << "Done" << endl;

return 0;


Here, I'm mixing all kinds of C and C++ code to make something ... work. I'm writing on
directly and using some C headers like
. Is this considered bad? Could undefined behavior arise? Is C code "compatible" with C++ so I just include it and use it?

The program works just fine.

Hello world!


Is this considered bad?

Some programmers consider it bad style to use C library functions when there are superior C++ library functions available. However, there are cases where it is better to use the C library functions.

Could undefined behavior arise?

Probably not. The C++ standard library incorporates almost the entire C standard library (with a few minor changes), so calls to C library functions from C++ are well-defined. As for functions such as write, their behaviour is defined by POSIX.

Is C code "compatible" with C++ so I just include it and use it?

For standard C library headers, yes. For implementation headers, typically yes; they are usually designed so that they can be validly included into C++ programs. For other headers... maybe. Not all C code is valid C++, but the degree of compatibility is high.