C\C++宏大全

1 宏的使用大全 宏,也叫宏定义,并不是C/C++语言本身的一部分,不能直接对宏进行编译。在编译程序前,必须先对宏进行预先的处理(专业术语叫作“预处理”)。预处理器会分析所有的源文件,当遇到宏名称严格匹配时,就会展开宏,也就是用定义好的文本来代替宏名称。宏的用途主要有三点:一是可以为程序员的开发提供一定的便利性;二是可以有效减少源文件中大量重复的、相似的代码;三是可以在一定程度上减少系统的开销,提高程序的运行效率。C/C++语言预定义了一些宏定义,常用的宏定义如下表。宏名称数据类型备注__FILE__字符串。 阅读详情

转自:http://www.cnblogs.com/sevencat/archive/2004/06/10/14872.html

 

一、标准预定义宏
The standard predefined macros are specified by the relevant language standards, so they are available with all compilers that implement those standards. Older compilers may not provide all of them. Their names all start with double underscores.

__FILE__
This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in #include or as the input file name argument. For example, "/usr/local/include/myheader.h" is a possible expansion of this macro.

__LINE__
This macro expands to the current input line number, in the form of a decimal integer constant. While we call it a predefined macro, it's a pretty strange macro, since its "definition" changes with each new line of source code.
__FILE__ and __LINE__ are useful in generating an error message to report an inconsistency detected by the program; the message can state the source line at which the inconsistency was detected. For example,

     fprintf (stderr, "Internal error: "
                      "negative string length "
                      "%d at %s, line %d.",
              length, __FILE__, __LINE__);
    
An #include directive changes the expansions of __FILE__ and __LINE__ to correspond to the included file. At the end of that file, when processing resumes on the input file that contained the #include directive, the expansions of __FILE__ and __LINE__ revert to the values they had before the #include (but __LINE__ is then incremented by one as processing moves to the line after the #include).

A #line directive changes __LINE__, and may change __FILE__ as well. See Line Control.

C99 introduces __func__, and GCC has provided __FUNCTION__ for a long time. Both of these are strings containing the name of the current function (there are slight semantic differences; see the GCC manual). Neither of them is a macro; the preprocessor does not know the name of the current function. They tend to be useful in conjunction with __FILE__ and __LINE__, though.


__DATE__
This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like "Feb 12 1996". If the day of the month is less than 10, it is padded with a space on the left.
If GCC cannot determine the current date, it will emit a warning message (once per compilation) and __DATE__ will expand to "??? ?? ????".


__TIME__
This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like "23:59:01".
If GCC cannot determine the current time, it will emit a warning message (once per compilation) and __TIME__ will expand to "??:??:??".


__STDC__
In normal operation, this macro expands to the constant 1, to signify that this compiler conforms to ISO Standard C. If GNU CPP is used with a compiler other than GCC, this is not necessarily true; however, the preprocessor always conforms to the standard unless the -traditional-cpp option is used.
This macro is not defined if the -traditional-cpp option is used.

On some hosts, the system compiler uses a different convention, where __STDC__ is normally 0, but is 1 if the user specifies strict conformance to the C Standard. CPP follows the host convention when processing system header files, but when processing user files __STDC__ is always 1. This has been reported to cause problems; for instance, some versions of Solaris provide X Windows headers that expect __STDC__ to be either undefined or 1. See Invocation.


__STDC_VERSION__
This macro expands to the C Standard's version number, a long integer constant of the form yyyymmL where yyyy and mm are the year and month of the Standard version. This signifies which version of the C Standard the compiler conforms to. Like __STDC__, this is not necessarily accurate for the entire implementation, unless GNU CPP is being used with GCC.
The value 199409L signifies the 1989 C standard as amended in 1994, which is the current default; the value 199901L signifies the 1999 revision of the C standard. Support for the 1999 revision is not yet complete.

This macro is not defined if the -traditional-cpp option is used, nor when compiling C++ or Objective-C.


__STDC_HOSTED__
This macro is defined, with value 1, if the compiler's target is a hosted environment. A hosted environment has the complete facilities of the standard C library available.

__cplusplus
This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to __STDC_VERSION__, in that it expands to a version number. A fully conforming implementation of the 1998 C++ standard will define this macro to 199711L. The GNU C++ compiler is not yet fully conforming, so it uses 1 instead. We hope to complete our implementation in the near future.

__OBJC__
This macro is defined, with value 1, when the Objective-C compiler is in use. You can use __OBJC__ to test whether a header is compiled by a C compiler or a Objective-C compiler.

__ASSEMBLER__
This macro is defined with value 1 when preprocessing assembly language.

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:

          /* Test for GCC > 3.2.0 */
          #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__)
          ...
          /* Test for GCC > 3.2.0 */
          #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的宏定义
VC的标准宏
The compiler recognizes 10 predefined ANSI C macros, and the Microsoft C++ implementation provides several more. These macros take no arguments and cannot be redefined. Their value, except for __LINE__ and __FILE__, must be constant throughout compilation. Some of the predefined macros listed below are defined with multiple values. See the following tables for more information.

ANSI-Compliant Predefined Macros

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 asctime declared in TIME.H.
 
__FILE__ The name of the current source file. __FILE__ expands to a string surrounded by double quotation marks.
You can create your own wide string version of __FILE__ as follows:

#include <stdio.h>
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFILE__ WIDEN(__FILE__)
wchar_t *pwsz = __WFILE__;

int main()
{
}
 
__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 and Date is an integer from 1 to 31.

微软的VC宏
_ATL_VER Defines the ATL version.
 
_CHAR_UNSIGNED Default char type is unsigned. Defined when /J is specified.
 
__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:

#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("\n%d",my_unique_prefix0);
   my_unique_prefix0++;
   printf("\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, /MLd, 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.

__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.

_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_IX86 Defined for x86 processors. See values for _M_IX86 for more details.

_M_IA64 Defined for 64-bit processors.

_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).
 
_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 Defines the major and minor versions of the compiler. For example, 1300 for Microsoft Visual C++ .NET. 1300 represents version 13 and no point release. This represents the fact that there have been a total of 13 releases of the compiler.
If you type cl /? at the command line, you will see the full version for the compiler you are using.
 
__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. 
_WCHAR_T_DEFINED
and

_NATIVE_WCHAR_T_DEFINED
 Defined when wchar_t is defined. Typically, wchar_t is defined when you use /Zc:wchar_t or when typedef unsigned short wchar_t; is executed in code.
 
_WIN32 Defined for applications for Win32 and Win64. Always defined. 

_WIN64 Defined for applications for Win64.

_Wp64 Defined when specifying /Wp64.

As shown in following table, the compiler generates a value for the preprocessor identifiers that reflect the processor option specified.

values for _M_IX86

Option in Development Environment Command-Line Option Resulting value
Blend /GB _M_IX86 = 600 (Default. Future compilers will emit a different value to reflect the dominant processor.)
Pentium /G5 _M_IX86 = 500
Pentium Pro, Pentium II, and Pentium III /G6 _M_IX86 = 600
80386 /G3 _M_IX86 = 300
80486 /G4 _M_IX86 = 400

 

C语言预定义宏大全 c语言中ANSI和microsoft预定义的宏名称和作用等 立即下载

相关推荐

手把手教你用STM32的ADC读取PT100模块,实现高精度温度采集(附完整代码)

本文详细介绍了如何利用STM32的ADC模块读取PT100温度传感器信号,实现高精度温度采集系统。从硬件选型、ADC配置校准到温度计算算法和软件滤波技术,提供完整的实现方案和优化技巧,帮助工程师快速构建稳定可靠的温度监测系统。

weixin_29185199的博客 344

VC\GCC宏一览

C\C++宏大全一、标准预定义宏The standard predefined macros are specified by the relevant language standards, so they are available with all compilers that implement those standards. Older compilers may not provid...

weixin_30872789的博客 264

【XR技术介绍】深度解析|AI眼镜核心技术架构:从硬件层到端云AI全链路拆解

本文将逐层拆解AI眼镜完整技术架构,梳理硬件、感知、光学、端侧AI、软件云端五大核心层级,剖析核心数据流与行业技术瓶颈,同时附上标准化技术架构图,适合技术学习、方案汇报、行业科普使用。

houdou112358的博客 433

“深入浅出”系列之C++:(28)C/C++中的宏定义

执行这个函数时,要获取被调用函数指定的地址(被调用函数的地址有一个范围,起始地址就是函数的入口地址,被调用函数从起始地址开始一步步往下执行),之后程序会跳转到被调函数的第一条语句,一步步往下依次执行被调函数中的语句,直到函数执行结束。实际的 5 * 5 相乘过程在编译阶段完成,而不是在预处理器工作阶段完成,宏不进行运算,它只是按照指令进行文字的替换操作,无论替换文本中是常数、表达式或者字符串等,预处理程序都不做任何检查,如果出现错误,只能是被宏代换之后的程序在编译阶段发现。函数参数类型检查严格。

weixin_65589140的博客 2441

vasp计算练习1-Si

si的vasp训练流程

qq_41074165的博客 3295

Ansys Zemax与Speos协同设计:HUD系统从光学优化到驾驶视觉验证全流程解析

本文详细解析了如何利用Ansys Zemax与Speos协同工作流,完成HUD系统从光学内核优化到驾驶视觉验证的全流程。通过Zemax进行精密光学设计与像差校正,再通过Speos进行HOA定量分析和虚拟驾驶舱仿真,实现了数据无损流转与验证闭环,有效解决了光学性能与视觉感知脱节的核心问题,显著提升HUD设计效率与可靠性。

git9versioner的博客 529

c++ 宏(macro)

宏的本质:编译前的文本替换机制  宏是一种在 预处理阶段(Preprocessing) 执行的代码替换工具。 

2402_88047672的博客 1520

万字长文告诉新手如何学习Python图像处理(上篇完结 四十四) | 「Python」有奖征文

这篇文章是图像处理的最后一篇文章,后面我们将进入新的章节。图像处理文章主要讲解的图像处理方法包括图像几何运算、图像量化采样、图像点运算、图像形态学处理、图像增强、图像平滑、图像锐化、图像特效、图像分割、傅里叶变换与霍夫变换、图像分类等。个人感觉如果你是编程初学者、Python初学者或图像处理爱好者,这个系列真心适合你学习,并且这篇文章算是Python图像处理的学习路线,希望您喜欢。

杨秀璋的专栏 2万+

ANSI C普通预定义宏

__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preproc

SHYBT'S BLOG 1423

Visual Studio调试技巧与实用方法总结(实战经验分享)

本文根据多年的项目实战经验,详细介绍一些Visual Studio常用的高效调试手段与技巧。

dvlinker的技术专栏 3万+

黑猫带你学UFS协议第8篇:UFS电气特性详解(Power、CLK、Reset等)

UFS强制支持secure mode。UFS设备可能会存储个人或者公司的信息,UFS提供把数据永久从设备上移除的功能,并且保证对存储介质进行逆向恢复数据也恢复不回来原有数据。安全模式是以逻辑单元为单位进行应用的,不同的逻辑单元可以有不同的安全模式。由于UFS设备的存储介质不同,所以把数据安全从存储介质上移除方式会有不同,spec提供了三种通用的移除方法,UFS设备至少支持其中一种。● 对存储的位置进行一次擦除操作。● 对存储的位置使用单一字符(比如0xAA)覆盖写,然后进行擦除。.........

黑猫奥利奥的博客 4075

C/C++基础:宏

(a > b)?return 0;(a > b)?return 0;(a > b)?(a > b)?a : b }?(a > b)?a : b }但是如果这个宏的替换列表很长呢?// 这是正确的实现// 这是正确的实现 # define max(a , b) {

qq_73143395的博客 2457

Allegro技巧----相同模块复用实现快速布局

使用Allegro软件进行PCB Layout设计时,当电路图中有很多路相同的模块,使用模块复用的的操作方法,可以显著提高工作效率,同时也可以使PCB布局在整体上显得美观。 如图,有8个相同的ADC采样电路模块,它们在原理图中的电路也是一样的,对于这多个相同的电路模块,如果一个个元器件布局很明显做了很多重复机械的劳动,效率低下;但是强大的Allegro软件早就考虑到了这点,只需要在PCB中做好其中的一个,则其余相同的模块通过复用的方式,可以快速完成,方便省事还美观。 具体步骤: 1.首先完成一个模块的PC

sinat_15677011的博客 5655

C语言宏的用法详解

1、简介 宏在C语言中是一段有名称的代码片段。无论何时使用到这个宏的时候,宏的内容都会被这段代码替换掉。主要有两种宏,他们的区别主要是在使用上面,一种是在使用时类似于数据对象称为Object-like,另一种在使用时类似于函数调用称为Function-like。在C语言使用#define来定义宏 你可以将任意的有效的标识符定义为宏,设置C语言的关键字也可以。但是在C语言中defined不可以作...

~~ LINUX ~~ 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

C\C++宏的优缺点

什么是宏? #define 机制包括了一个规定,允许把参数替换到文本中,这种实现通常称为宏(macro) 或定义宏(define macro) 声明方式:#define name( parament-list ) stuff 其中的 parament-list 是一个由逗号隔开的符号表,它们可能出现在stuff中,参数列表的左括号必须与name紧邻。如果两者之间有任何空白存在,参数列表就会被...

Pin_na 1999

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

C/C++中的预定义宏

预定义宏是由编译器自动定义的标识符,它们包含了编译器、操作系统、文件名、行号等编译时信息。开发者可以直接在代码中使用这些宏,而无需手动定义。C语言/C++中的预定义宏LINE描述:当前源代码行号。return 0;FILE描述:当前源文件名。return 0;DATE描述:编译的日期。return 0;TIME描述:编译的时间。return 0;STDC描述:如果定义了该宏,则表明编译器符合ANSI C标准。

imoisture的博客 1180

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

c++中.cpp\.c\.h\.hpp文件

告别cpp&h:hpp文件编写心得

qq_42697866的博客 1156

C 的宏和 C++的宏

总结一下C和C++的宏。 大家经常使用的其实都是C中的宏,但是C++都延续了下来,先回顾一下。 #define :定义宏 #undef :取消宏 #include :包含头文件 #ifdef 如果宏已经定义,则返回真 #ifndef 如果宏没有定义,则返回真 #if 如果条件为真,则执行下面的 #else 与#if互斥使用 #elif 相当于我们使用的else if #endi...

phenixyf的专栏 495

C语言专题之宏的基本概念

宏定义是C/C++语言中一项强大而灵活的特性,它允许程序员使用预处理器指令来创建简化的代码表示。这种机制不仅提高了代码的可读性和可维护性,还能在某些情况下优化程序性能。#define 标识符 替换文本其中,“标识符”是用户定义的宏名,“替换文本”则是宏被调用时将被替换的内容。值得注意的是,宏定义并非C/C++语言的标准语句,而是一种预处理指令,因此在使用时无需在行末添加分号。类型描述无参数宏仅包含常量表达式带参数宏可接受参数,类似于函数。

2401_89278589的博客 1793

vscode运行cpp文件:检测到 #include 错误。请更新 includePath。已为此翻译单元(E:\C++ Code\test1\test1\test1.cpp)禁用波形曲线。

刚为vscode配置好C++编译环境准备刷leetcode,结果写cpp文件时发现#include头文件总是报错: 我就很迷惑了,#include<iostream>也能出错,找了半天教程,特此记录: 打开.vscode文件夹里面的c_cpp_properties.json 将里面的“compilepath”值改为mingw的路径: 即可正常运行了。 参考文章...

weixin_41174502的博客 2万+

C/C++ 中的宏/Macro

宏(Macro)本质上就是代码片段,通过别名来使用。在编译前的预处理中,宏会被替换为真实所指代的代码片段,即下图中 Preprocessor 处理的部分。 C/C++ 代码编译过程 - 图片来自ntu.edu.sg 根据用法的不同,分两种,Object-like 和 Function-like。前者用于 Object 对象,后者用于函数方法。 C/C++ 代码编译过程中,可通过相应参数...

Abelia的博客 730

C与C++编译的区别 C和C++混合编译

原文链接,文章不错,修改了排版,看起来更加舒服。 关于extern_C 通常,在C语言的头文件中经常可以看到类似下面这种形式的代码: #ifdef __cplusplus extern "C" { #endif /**** some declaration or so *****/ #ifdef __cplusplus } #endif /* end of __cplusplus */ 那么,这种写法什么用呢?实际上,这是为了让CPP能够与C接口而采用的一种语法形式。之..

hpuzsk的博客 3488

宏之双刃剑:C/C++ 预处理器宏的威力、陷阱与现代化演进全解

本文系统梳理C/C++宏的七类核心用法:常量宏、函数式宏、条件编译、字符串化/拼接、可变参数宏、调试宏和防御性宏。深入分析各类宏的优势、典型陷阱及现代C++替代方案,指出宏在跨平台编译、调试开关等场景仍不可替代,但需警惕副作用、命名污染等问题。提出"能不用则不用,必须用则封装好"的黄金法则,帮助开发者在性能与安全间取得平衡,写出高效可靠的代码。

聚焦前沿科技与硬核技术底层拆解,深耕 AI、量子计算、WebAssembly 等核心领域,拒绝碎片化科普。以通俗语言讲透复杂原理,用干货内容拆解技术逻辑,助力从业者吃透核心、把握趋势,每篇都是可落地的深度技术沉淀。 1566
上一篇: C语言几种 预定义宏
下一篇: C语言中typedef用法
Theodore_Lin
博客等级 码龄16年 24粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值