Skip to the content.

预定义宏

1. __LINE__&__FILE__

__LINE__是当前代码所在的行,__FILE__是指代码所在的文件名。示例(C语言):

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("%d\n", __LINE__);
  printf("%s\n", __FILE__);
  return 0;
}

输出:

5
predefined_test.cc

2. __TIME__&__DATE__

__TIME__指系统当前时间(有:时分秒),__DATE__是系统当前日期(有:年月日)。示例(C语言):

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("%s\n", __DATE__);
  printf("%s\n", __TIME__);

  return 0;
}

输出:

Apr  4 2020
22:42:06

3.__STDC__

当程序是标准C程序时,__STDC__为1。示例(C语言):

#include <stdio.h>

int main(int argc, char *argv[])
{
  printf("%s\n", __STDC__);

  return 0;
}

输出:

1

4.__cplusplus

当程序是C++程序时,该宏才有定义,且为C++版本号。示例(C++语言):

#include <stdio.h>

int main(int argc, char *argv[]) {
  printf("%ld\n", __cplusplus);

  return 0;
}

当编译命令为:

g++ test.cc -o test -std=c++11

输出:

201103

当编译命令为:

g++ test.cc -o test -std=c++17

输出:

201703

5.__VA_ARGS__&##__VA_ARGS__(只能在宏中使用)

__VA_ARGS__和##__VA_ARGS__都可以用在可变参数替换宏中。

__VA_ARGS__可以将省略号(…)的内容照抄下来,此时不可以使用##__VA_ARGS__。

#define LOG1(...) printf(##__VA_ARGS__)

LOG1("pi is %d.\n", 3);
LOG1("log1\n");

当可变参数的个数为0时,##__VA_ARGS__可以省略前面的逗号,即format后面的逗号错误示例:

#define LOG2(format, ...) printf(format, __VA_ARGS__)

LOG2("log2\n");

这种写法会在编译(准确说是预编译)时报错。

示例(C语言):

#include <stdio.h>

#define LOG1(...) printf(__VA_ARGS__)
#define LOG2(format, ...) printf(format, ##__VA_ARGS__)

int main(int argc, char *argv[])
{
  LOG1("pi is %d.\n", 3);
  LOG1("log1\n");
  LOG2("log2\n");
  LOG2("pi is %f.\n", 3.141592);

  return 0;
}

输出:

pi is 3.
log1
log2
pi is 3.141592.