题
{net04:~/xxxx/wip} gcc -o write_test write_test.c
In file included from write_test.c:4:
global.h:10: warning: `b' initialized and declared `extern'
此代码使用 fcntl.h 和定义的文件处理函数 - 如 open()、write()、close() 等。代码按预期编译并运行。
{net04:~/xxxx/wip} gcc -o write_test write_test.cpp
In file included from write_test.cpp:4:
global.h:10: warning: `b' initialized and declared `extern'
write_test.cpp: In function `int main()':
write_test.cpp:56: error: `exit' undeclared (first use this function)
write_test.cpp:56: error: (Each undeclared identifier is reported only once for each function it appears in.)
write_test.cpp:58: error: `write' undeclared (first use this function)
write_test.cpp:62: error: `close' undeclared (first use this function)
当我使用它作为CPP源代码时,为什么GCC会抱怨?奇怪的是,为什么它不抱怨 open() ?这里到底发生了什么?
解决方案
C++ 对标头更加严格 - 你需要:
#include <unistd.h>
正确获得指示的功能。global.h
不应该定义 b - 标头不应该初始化变量。编译时应该使用
-Wall -Werror
这将迫使您修复代码中所有不可靠的部分。要得到
exit()
干净地你需要#include <cstdlib>
(C++) 或#include <stdlib.h>
(C)使用
g++
链接 C++ 代码以便包含 C++ 库。可能最容易进行整个 C++ 编译g++
.
不隶属于 StackOverflow