You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何__USE_MISC被stdio.h取消定义、M_PI被math.h取消定义?及相关编译问题咨询

为何__USE_MISC被stdio.h取消定义、M_PI被math.h取消定义?及相关编译问题咨询

我有如下代码:

#define __USE_MISC

#ifdef __USE_MISC
#pragma message("C Preprocessor got here!")
#endif

#include <stdio.h>

#ifdef __USE_MISC
#pragma message("C Preprocessor made it here too!")
#endif

#include <math.h>

int main(void) {
  double x = M_PI;
  printf("x = %lf \n", x);
  return 0;
}

当我用以下命令编译时:

$ gcc test.c -std=c23 -Wall -pedantic
test.c:4:9: note: ‘#pragma message: C Preprocessor got here!’
    4 | #pragma message("C Preprocessor got here!")
      |         ^~~~~~~
test.c: In function ‘main’:
test.c:16:14: error: ‘M_PI’ undeclared (first use in this function)
   16 |   double x = M_PI;
      |              ^~~~
test.c:16:14: note: each undeclared identifier is reported only once for each function it appears in

为什么使用<stdio.h>会取消__USE_MISC宏的定义?而如果我改用以下编译命令,这个问题就消失了?

$ gcc test.c  -Wall -pedantic
test.c:4:9: note: ‘#pragma message: C Preprocessor got here!’
    4 | #pragma message("C Preprocessor got here!")
      |         ^~~~~~~
test.c:10:9: note: ‘#pragma message: C Preprocessor made it here too!’
   10 | #pragma message("C Preprocessor made it here too!")
      |         ^~~~~~~

我了解到__USE_MISC可能会被某些头文件取消定义,但至少不是被<stdio.h>直接调用的文件导致的,不过确实有不少头文件会被间接调用。

更新:我发现所有的__USE_*宏都会被#include<stdio.h>取消定义。我还尝试了以下代码:

#define __USE_MISC

#include <math.h>

#ifndef M_PI
#pragma message("C Preprocessor can not find M_PI!")
#endif

#ifndef __USE_MISC
#pragma message("C Preprocessor finds __USE_MISC to be undefined")
#endif

int main(void) {
  double x = M_PI;
  x += 1;
}

这里仅包含<math.h>时,__USE_MISC和M_PI也被取消定义了:

test.c:6:9: note: ‘#pragma message: C Preprocessor can not find M_PI!’
    6 | #pragma message("C Preprocessor can not find M_PI!")
      |         ^~~~~~~
test.c:10:9: note: ‘#pragma message: C Preprocessor finds __USE_MISC to be undefined’
   10 | #pragma message("C Preprocessor finds __USE_MISC to be undefined")
      |         ^~~~~~~
test.c: In function ‘main’:
test.c:14:14: error: ‘M_PI’ undeclared (first use in this function)
   14 |   double x = M_PI;
      |              ^~~~
test.c:14:14: note: each undeclared identifier is reported only once for each function it appears in

为什么会出现这种情况?但如果先包含<stdio.h>再定义__USE_MISC就不会有问题?

另外,为什么我指定任意标准(我试过c89、c90、c99、c17、c23)甚至用-ansi都会有这个问题?

如果用户不应该指定__USE_MISC,那我该怎么让M_PI被定义?

提前感谢您的帮助!

备注:内容来源于stack exchange,提问作者user3236841

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 18:09:33