typedef
If it is placed outside all functions, its scope is from the beginning of its definition until the end of the file;
If placed within a function, the defined field is defined from the beginning of the definition until the end of the function;
#define:
Scopes are defined from the beginning of the definition to the end of the entire file, whether within a function or outside of all functions.
Define within the same compilation unit, even in different namespaces, the scope of the action is the same. That is, from definition to file introduction.
Look at the following example:
Main.cpp
/** * @file Main.cpp * @author Chenjiashou ([email protected]) * @date 2017/09/19 17:37:33 * @version $Revision $ * @brie F * **/#include<iostream>#include"Test1.h"#defineLL 2typedefLong Longll;voidTest_typedef () {typedefintX_int;x_int a=1;}namespaceOther {#defineOther//Don't care if you're in a namespace//Key in a compilation unit}intMain () {#ifdef LL std::cout<<"LL Define"<<Std::endl;#endif#ifdef SS std::cout<<"SS Define"<<Std::endl;#endif#ifdef Other Std::cout<<"Other define"<<Std::endl;#endifll a=1; Print (); //X_int b = 1;//Compile Error return 0;}/*vim:set ts=4 sw=4 sts=4 tw=100*/
Test1.h
/* * * @file test1.h * @author Chenjiashou ([email protected]) * @date 2017/09/19 17:39:05 * @version $Revision $ * @br Ief * **/#ifndef test1_h#define test1_h#endif // Test1_h void print (); /* */
Test1.cpp
/** * @file test1.cpp * @author Chenjiashou ([email protected]) * @date 2017/09/19 17:36:15 * @version $Revision $ * @br IEF * **/#include<iostream>#defineSS 1voidprint () {#ifdef SS std::cout<<"SS Define"<<Std::endl;#endif#ifdef LL std::cout<<"LL Define"<<Std::endl;#endif//ll C = 1;//Compile Error//std::cout << c << Endl;}/*vim:set ts=4 sw=4 sts=4 tw=100*/
Final Result:
LL Defineother definess Define
Scope of C + + typedef and # define