1
{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()?这里到底发生了什么?

4

1 回答 1

7
  1. C++ 对标头更严格 - 您需要:#include <unistd.h>正确获取指示的功能。

  2. global.h不应定义 b - 标头不应初始化变量。

  3. 编译时应该使用-Wall -Werror,这将迫使您修复代码中所有不可靠的部分。

  4. exit()干净利落,您需要#include <cstdlib>(C++) 或#include <stdlib.h>(C)

  5. 用于g++链接 C++ 代码,以便包含 C++ 库。使用g++.

于 2009-11-16T07:51:56.277 回答