文档章节

C++预定义宏 C++ Predefined Macros

涩女郎
 涩女郎
发布于 2015/08/25 08:52
字数 2427
阅读 194
收藏 3

一、ANSI C标准预定义宏

 

__LINE__:在源代码中插入当前源代码行号;

__FILE__:在源文件中插入当前源文件名;

__DATE__:在源文件中插入当前的编译日期

__TIME__:在源文件中插入当前编译时间;

__STDC__:当要求程序严格遵循ANSI C标准时该标识被赋值为1,表明是标准的C程序;

//__cplusplus:当编写C++程序时该标识符被定义,表明是标准的C++程序。(这个是VC的吧?)

 

MSDN上的解释

Macro
Description

__DATE__
The compilation date of the current source file. The date is a string literal of the form Mmm dd yyyy. The month name Mmm is the same as for dates generated by the library function asctimedeclared in TIME.H.

__FILE__
The name of the current source file. __FILE__ expands to a string surrounded by double quotation marks.

__LINE__
The line number in the current source file. The line number is a decimal integer constant. It can be altered with a #line directive.

__STDC__
Indicates full conformance with the ANSI C standard. Defined as the integer constant 1 only if the /Za compiler option is given and you are not compiling C++ code; otherwise is undefined.

__TIME__
The most recent compilation time of the current source file. The time is a string literal of the form hh:mm:ss.

__TIMESTAMP__
The date and time of the last modification of the current source file, expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy, where Ddd is the abbreviated day of the week andDate is an integer from 1 to 31.

 

一个例子:

#include <iostream>
using namespace std;
int main(int argc,char** argv)
{
    cout << "__FILE__ = " << __FILE__ << endl;
    cout << "__DATE__ = " << __DATE__ << endl;
    cout << "__TIME__ = " << __TIME__ << endl;
    cout << "__LINE__ = " << __LINE__ << endl;
    #if defined(__cplusplus)
        cout<<"在此环境中可以编缉和调试标准C++程序。"<<endl;
    #endif
    #if defined(__STDC__)
        cout<<"在此环境中可以编缉和调试标准C程序。"<<endl;
    #endif
    return EXIT_SUCCESS;
}

//---------------------------------------------------------------------------------------------------------------------------------------------------

二、GCC 中普通预定义宏(不了解。。)


__GNUC__
__GNUC_MINOR__
__GNUC_PATCHLEVEL__
These macros are defined by all GNU compilers that use the C preprocessor: C, C++, and Objective-C. Their values are the major version, minor version, and patch level of the compiler, as integer constants. For example, GCC 3.2.1 will define __GNUC__ to 3, __GNUC_MINOR__ to 2, and __GNUC_PATCHLEVEL__ to 1. They are defined only when the entire compiler is in use; if you invoke the preprocessor directly, they are not defined.
__GNUC_PATCHLEVEL__ is new to GCC 3.0; it is also present in the widely-used development snapshots leading up to 3.0 (which identify themselves as GCC 2.96 or 2.97, depending on which snapshot you have).

If all you need to know is whether or not your program is being compiled by GCC, you can simply test __GNUC__. If you need to write code which depends on a specific version, you must be more careful. Each time the minor version is increased, the patch level is reset to zero; each time the major version is increased (which happens rarely), the minor version and patch level are reset. If you wish to use the predefined macros directly in the conditional, you will need to write it like this:

         
          #if __GNUC__ > 3 || \
              (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 || \
                                 (__GNUC_MINOR__ == 2 && \
                                  __GNUC_PATCHLEVEL__ > 0))
Another approach is to use the predefined macros to calculate a single number, then compare that against a threshold:

          #define GCC_VERSION (__GNUC__ * 10000 \
                               + __GNUC_MINOR__ * 100 \
                               + __GNUC_PATCHLEVEL__)
          ...
         
          #if GCC_VERSION > 30200
Many people find this form easier to understand.

__GNUG__
The GNU C++ compiler defines this. Testing it is equivalent to testing (__GNUC__ && __cplusplus).

__STRICT_ANSI__
GCC defines this macro if and only if the -ansi switch, or a -std switch specifying strict conformance to some version of ISO C, was specified when GCC was invoked. It is defined to 1. This macro exists primarily to direct GNU libc's header files to restrict their definitions to the minimal set found in the 1989 C standard.

__BASE_FILE__
This macro expands to the name of the main input file, in the form of a C string constant. This is the source file that was specified on the command line of the preprocessor or C compiler.

__INCLUDE_LEVEL__
This macro expands to a decimal integer constant that represents the depth of nesting in include files. The value of this macro is incremented on every #include directive and decremented at the end of every included file. It starts out at 0, it's value within the base file specified on the command line.

__ELF__
This macro is defined if the target uses the ELF object format.

__VERSION__
This macro expands to a string constant which describes the version of the compiler in use. You should not rely on its contents having any particular form, but it can be counted on to contain at least the release number.

__OPTIMIZE__
__OPTIMIZE_SIZE__
__NO_INLINE__
These macros describe the compilation mode. __OPTIMIZE__ is defined in all optimizing compilations. __OPTIMIZE_SIZE__ is defined if the compiler is optimizing for size, not speed. __NO_INLINE__ is defined if no functions will be inlined into their callers (when not optimizing, or when inlining has been specifically disabled by -fno-inline).
These macros cause certain GNU header files to provide optimized definitions, using macros or inline functions, of system library functions. You should not use these macros in any way unless you make sure that programs will execute with the same effect whether or not they are defined. If they are defined, their value is 1.

__CHAR_UNSIGNED__
GCC defines this macro if and only if the data type char is unsigned on the target machine. It exists to cause the standard header file limits.h to work correctly. You should not use this macro yourself; instead, refer to the standard macros defined in limits.h.

__WCHAR_UNSIGNED__
Like __CHAR_UNSIGNED__, this macro is defined if and only if the data type wchar_t is unsigned and the front-end is in C++ mode.

__REGISTER_PREFIX__
This macro expands to a single token (not a string constant) which is the prefix applied to CPU register names in assembly language for this target. You can use it to write assembly that is usable in multiple environments. For example, in the m68k-aout environment it expands to nothing, but in the m68k-coff environment it expands to a single %.

__USER_LABEL_PREFIX__
This macro expands to a single token which is the prefix applied to user labels (symbols visible to C code) in assembly. For example, in the m68k-aout environment it expands to an _, but in the m68k-coff environment it expands to nothing.
This macro will have the correct definition even if -f(no-)underscores is in use, but it will not be correct if target-specific options that adjust this prefix are used (e.g. the OSF/rose -mno-underscores option).

__SIZE_TYPE__
__PTRDIFF_TYPE__
__WCHAR_TYPE__
__WINT_TYPE__
These macros are defined to the correct underlying types for the size_t, ptrdiff_t, wchar_t, and wint_t typedefs, respectively. They exist to make the standard header files stddef.h and wchar.h work correctly. You should not use these macros directly; instead, include the appropriate headers and use the typedefs.

__CHAR_BIT__
Defined to the number of bits used in the representation of the char data type. It exists to make the standard header given numerical limits work correctly. You should not use this macro directly; instead, include the appropriate headers.

__SCHAR_MAX__
__WCHAR_MAX__
__SHRT_MAX__
__INT_MAX__
__LONG_MAX__
__LONG_LONG_MAX__
Defined to the maximum value of the signed char, wchar_t, signed short, signed int, signed long, and signed long long types respectively. They exist to make the standard header given numerical limits work correctly. You should not use these macros directly; instead, include the appropriate headers.

__USING_SJLJ_EXCEPTIONS__
This macro is defined, with value 1, if the compiler uses the old mechanism based on setjmp and longjmp for exception handling.

__NEXT_RUNTIME__
This macro is defined, with value 1, if (and only if) the NeXT runtime (as in -fnext-runtime) is in use for Objective-C. If the GNU runtime is used, this macro is not defined, so that you can use this macro to determine which runtime (NeXT or GNU) is being used.

__LP64__
_LP64
These macros are defined, with value 1, if (and only if) the compilation is for a target where long int and pointer both use 64-bits and int uses 32-bit.

 

//---------------------------------------------------------------------------------------------------------------------------------------------------

三、微软的VC宏(从MSDN复制过来)


Macro
Description

_ATL_VER

Defines the ATL version.

_CHAR_UNSIGNED

Default char type is unsigned. Defined when /J is specified.

__CLR_VER

Defines the version of the common language runtime used when the application was compiled. The value returned will be in the following format:

Mmmbbbbb

where,

M is the major version of the runtime.

mm is the minor version of the runtime.

bbbbb is the build number.

// clr_ver.cpp
// compile with: /clr
using namespace System;
int main() {
   Console::WriteLine(__CLR_VER);
}

__cplusplus_cli

Defined when compiling with /clr/clr:pure, or /clr:safe. Value of __cplusplus_cli is 200406. __cplusplus_cli is in effect throughout the translation unit.

// cplusplus_cli.cpp
// compile with: /clr
#include "stdio.h"
int main() {
   #ifdef __cplusplus_cli
      printf("%d\n", __cplusplus_cli);
   #else
      printf("not defined\n");
   #endif
}

__COUNTER__

Expands to an integer starting with 0 and incrementing by 1 every time it is used in a compiland.__COUNTER__ remembers its state when using precompiled headers. If the last __COUNTER__ value was 4 after building a precompiled header (PCH), it will start with 5 on each PCH use.

__COUNTER__ lets you generate unique variable names. You can use token pasting with a prefix to make a unique name. For example:

// pre_mac_counter.cpp
#include <stdio.h>
#define FUNC2(x,y) x##y
#define FUNC1(x,y) FUNC2(x,y)
#define FUNC(x) FUNC1(x,__COUNTER__)

int FUNC(my_unique_prefix);
int FUNC(my_unique_prefix);

int main() {
   my_unique_prefix0 = 0;
   printf_s("\n%d",my_unique_prefix0);
   my_unique_prefix0++;
   printf_s("\n%d",my_unique_prefix0);
}

__cplusplus

Defined for C++ programs only.

_CPPLIB_VER

Defined if you include any of the C++ Standard Library headers; reports which version of the Dinkumware header files are present.

_CPPRTTI

Defined for code compiled with /GR (Enable Run-Time Type Information).

_CPPUNWIND

Defined for code compiled with /GX (Enable Exception Handling).

_DEBUG

Defined when compiling with /LDd, /MDd, and /MTd.

_DLL

Defined when /MD or /MDd (Multithread DLL) is specified.

__FUNCDNAME__

Valid only within a function and returns the decorated name of the enclosing function (as a string). __FUNCDNAME__ is not expanded if you use the /EP or /P compiler option.

__FUNCSIG__

Valid only within a function and returns the signature of the enclosing function (as a string).__FUNCSIG__ is not expanded if you use the /EP or /P compiler option.

On a 64-bit operating system, the calling convention is __cdecl by default.

__FUNCTION__

Valid only within a function and returns the undecorated name of the enclosing function (as a string). __FUNCTION__ is not expanded if you use the /EP or /P compiler option.

_INTEGRAL_MAX_BITS

Reports the maximum size (in bits) for an integral type.

// integral_max_bits.cpp
#include <stdio.h>
int main() {
   printf("%d\n", _INTEGRAL_MAX_BITS);
}

_M_ALPHA

Defined for DEC ALPHA platforms. It is defined as 1 by the ALPHA compiler, and it is not defined if another compiler is used.

_M_CEE

Defined for a compilation that uses any form of /clr (/clr:oldSyntax/clr:safe, for example).

_M_CEE_PURE

Defined for a compilation that uses /clr:pure.

_M_CEE_SAFE

Defined for a compilation that uses /clr:safe.

_M_IX86

Defined for x86 processors. See Values for _M_IX86 for more details.

_M_IA64

Defined for Itanium Processor Family 64-bit processors.

_M_IX86_FP

Expands to a value indicating which /arch compiler option was used:

  • 0 if /arch was not used.

  • 1 if /arch:SSE was used.

  • 2 if /arch:SSE2 was used.

  • See /arch (Minimum CPU Architecture) for more information.

_M_MPPC

Defined for Power Macintosh platforms (no longer supported).

_M_MRX000

Defined for MIPS platforms (no longer supported).

_M_PPC

Defined for PowerPC platforms (no longer supported).

_M_X64

Defined for x64 processors.

_MANAGED

Defined to be 1 when /clr is specified.

_MFC_VER

Defines the MFC version. For example, 0x0700 represents MFC version 7.

_MSC_EXTENSIONS

This macro is defined when compiling with the /Ze compiler option (the default). Its value, when defined, is 1.

_MSC_VER

Reports the major and minor versions of the compiler. For example, 1310 for Microsoft Visual C++ .NET 2003. 1310 represents version 13 and a 1.0 point release. The current compiler version is 1400.

Type cl /? at the command line to see the major and minor versions of your compiler along with the build number.

__MSVC_RUNTIME_CHECKS

Defined when one of the /RTC compiler options is specified.

_MT

Defined when /MD or /MDd (Multithreaded DLL) or /MT or /MTd (Multithreaded) is specified.

_NATIVE_WCHAR_T_DEFINED

Defined when /Zc:wchar_t is used.

_OPENMP

Defined when compiling with /openmp, returns an integer representing the date of the OpenMP specification implemented by Visual C++. // _OPENMP_dir.cpp // compile with: /openmp #include <stdio.h> int main() { printf("%d\n", _OPENMP); }sdOutput200203

_VC_NODEFAULTLIB

Defined when /Zl is used; see /Zl (Omit Default Library Name) for more information.

_WCHAR_T_DEFINED

Defined when /Zc:wchar_t is used or if wchar_t is defined in a system header file included in your project.

_WIN32

Defined for applications for Win32 and Win64. Always defined.

_WIN64

Defined for applications for Win64.

_Wp64

Defined when specifying /Wp64.

 

//---------------------------------------------------------------------------------------------------------------------------------------------------

四、应用

ogre的代码,里面的class Exception就用

 

if( !m_pBuffer )
{
   OGRE_EXCEPT(
        Exception::ERR_INTERNAL_ERROR,
        "Can not flip an unitialized texture",
        "Image::flipAroundX" );
}

 

可以看到OGRE_EXCEPT的定义:

#ifndef OGRE_EXCEPT
#define OGRE_EXCEPT(num, desc, src) throw Ogre::ExceptionFactory::create( \
    Ogre::ExceptionCodeType<num>(), desc, src, __FILE__, __LINE__ );
#endif

 

 

static InternalErrorException create(
    ExceptionCodeType<Exception::ERR_INTERNAL_ERROR> code,
    const String& desc,
    const String& src, const char* file, long line)
{
    return InternalErrorException(code.number, desc, src, file, line);
}

 

这样出现异常,可以很方便地追踪日志或者代码。

 

//---------------------------------------------------------------------------------------------------------------------------------------------------

说明:

对GCC的宏完全没有接触,VC中的知道的就那么几个,只是粘贴了过来。

参考的或者重制的地址:

http://blog.csdn.net/winux/archive/2006/07/03/871645.aspx

http://blog.ednchina.com/haishilan/130828/message.aspx

http://hi.baidu.com/plutus666/blog/item/f864800995e3c1d862d98627.html

http://blog.chinaunix.net/u2/62918/showart_495634.html

© 著作权归作者所有

共有 人打赏支持
涩女郎
粉丝 35
博文 104
码字总数 160210
作品 0
浦东
高级程序员
C语言基础教程之预定义和宏处理

define看起来很炫酷!C语言基础教程之预处理和宏定义 C语言预处理器 C语言预处理器不是编译器的组成部分,但是它是编译过程中一个单独的步骤。简言之,C语言预处理器只不过是一个文本替换工具...

这个人很懒什么都没留下
08/18
0
0
模板函数min/max与Visual C++中的 min/max宏冲突

错误输出: error C2589: “(”: “::”右边的非法标记 error C2059: 语法错误 : “::” 错误原因 函数模板max与Visual C++中的全局的宏max冲突。 解决办法 第一种办法: 设置项目属性,在预定...

摩西.M
2014/01/21
0
0
C语言编程学习—宏定义的一些使用技巧

C语言是面向过程的,而C++是面向对象的 C和C++的区别: C是一个结构化语言,它的重点在于算法和数据结构。C程序的设计首要考虑的是如何通过一个过程,对输入(或环境条件)进行运算处理得到...

小辰带你看世界
03/24
0
0
gcc和g++编译c或者c++文件碰到的问题

gcc和g++都是GNU(组织)的一个编译器。 误区一:gcc只能编译c代码,g++只能编译c++代码 两者都可以,但是请注意: 1.后缀为.c的,gcc把它当作是C程序,而g++当作是c++程序;后缀为.cpp的,两者都...

peterli
2012/08/26
0
0
gcc和g++的区别 (很详细的描述)

gcc和g++都是GNU(组织)的一个编译器。 误区一:gcc只能编译c代码,g++只能编译c++代码 两者都可以,但是请注意: 1.后缀为.c的,gcc把它当作是C程序,而g++当作是c++程序;后缀为.cpp的,两者都...

AlphaJay
2010/04/20
0
2

没有更多内容

加载失败,请刷新页面

加载更多

70.shell的函数 数组 告警系统需求分析

20.16/20.17 shell中的函数 20.18 shell中的数组 20.19 告警系统需求分析 20.16/20.17 shell中的函数: ~1. 函数就是把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段...

王鑫linux
今天
2
0
分布式框架spring-session实现session一致性使用问题

前言:项目中使用到spring-session来缓存用户信息,保证服务之间session一致性,但是获取session信息为什么不能再服务层获取? 一、spring-session实现session一致性方式 用户每一次请求都会...

WALK_MAN
今天
5
0
C++ yield()与sleep_for()

C++11 标准库提供了yield()和sleep_for()两个方法。 (1)std::this_thread::yield(): 线程调用该方法时,主动让出CPU,并且不参与CPU的本次调度,从而让其他线程有机会运行。在后续的调度周...

yepanl
今天
4
0
Java并发编程实战(chapter_3)(线程池ThreadPoolExecutor源码分析)

这个系列一直没再写,很多原因,中间经历了换工作,熟悉项目,熟悉新团队等等一系列的事情。并发课题对于Java来说是一个又重要又难的一大块,除非气定神闲、精力满满,否则我本身是不敢随便写...

心中的理想乡
今天
33
0
shell学习之获取用户的输入命令read

在运行脚本的时候,命令行参数是可以传入参数,还有就是在脚本运行过程中需要用户输入参数,比如你想要在脚本运行时问个问题,并等待运行脚本的人来回答。bash shell为此提 供了read命令。 ...

woshixin
今天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部