在C ++中使用为C创建的Linux API标头

Gal*_*ala 4 c c++ linux

让我们考虑这段代码:

#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) {
        perror("write");
    }

    cout << "Done" << endl;

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

在这里,我混合了各种C和C ++代码以使某些事情起作用。我正在stdout直接写代码,并使用一些C标头,例如string.hstdio.h。这算不好吗?会出现不确定的行为吗?C代码是否与C ++“兼容”,所以我只包含它并使用它?

该程序工作正常。

Hello world!
Done
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 5

这算不好吗?

当有高级C ++库函数可用时,某些程序员认为使用C库函数是不好的样式。但是,在某些情况下,最好使用C库函数。

会出现不确定的行为吗?

可能不会。C ++标准库几乎包含了整个C标准库(有一些小的更改),因此从C ++到C库函数的调用是明确定义的。至于的功能write,它们的行为由POSIX定义。

C代码是否与C ++“兼容”,所以我只包含它并使用它?

对于标准C库标头,可以。对于实现标头,通常为yes;它们通常被设计为可以有效地包含在C ++程序中。对于其他标题...也许。并非所有的C代码都是有效的C ++,但是兼容性程度很高。