与 c 代码相比,为什么 c + + 代码不需要"# define POSIX c source 200809L"?

When I use "POSIX interval timer" or do signal handling, I have to insert

#define _POSIX_C_SOURCE 200809L

on line 1 inside any of my files. But I figured out that only C code needs it, but not in C++ code.

How does the g++ compiler work differently from the gcc compiler on this issue?


below is my system environment

 user@~ $ g++ --version
 g++ (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
 Copyright (C) 2015 Free Software Foundation, Inc.
 This is free software; see the source for copying conditions.
 There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

and I build the project adding this line in CMakeLists.txt

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -std=c++14 -Wall")

转载于:https://stackoverflow.com/questions/53037824/in-contrast-to-c-code-why-c-code-doesnt-need-define-posix-c-source-200809

Let's do a simple experiment. Try to compile this short source file:

auto f()
{
    return _POSIX_C_SOURCE;
}

Nope. It doesn't compile since _POSIX_C_SOURCE is not defined.

But what if we include a C++ header?

#include <iostream>

auto f()
{
    return _POSIX_C_SOURCE;
}

It compiles well.

(Try it live: https://godbolt.org/z/C6_a6P)

That means it has nothing to do with g++. Somewhere in some of the C++ standard library header files, this macro is defined.

g++ defines _GNU_SOURCE, which defines _POSIX_C_SOURCE.

This is done because it is required by the standard c++ template library.

Fuller discussion at https://gcc.gnu.org/bugzilla/show_bug.cgi?id=2082

Description of the macros at https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html