Use the compiler to use macro variables

Source: Internet
Author: User

Link: http://www.cppblog.com/jialisoft/archive/2012/10/04/192742.html

    1. # Include <stdio. h>
    2. IntMain (IntArgc,Char** Argv)
    3. {
    4. # Ifdef my_mac
    5. Printf ("hello-D. \ n ");
    6. # Else
    7. Printf ("my_mac was not defined. \ n ");
    8. # Endif
    9. Return 0;
    10. }

The aboveCodeMy_mac macro is used,

 

[] $ G ++-dmy_mac-O Dtest. c

Execution result:

 

    1. [] $./Dtest
    2. Hello-D.
    3. [] $

If the-D option is not set, re-compile and execute the result:

 

    1. [] $ G ++./Dtest. C-o Dtest
    2. [] $./Dtest
    3. My_mac was not defined.


We can use the compiler option to debug ourProgramAO.

 

What if my macro represents a constant ??

Check the modified Code:

 

    1. # Include <stdio. h>
    2. IntMain (IntArgc,Char** Argv)
    3. {
    4. # Ifdef my_mac
    5. Printf ("hello-D. % d \ n", my_mac );
    6. # Else
    7. Printf ("my_mac was not defined. \ n ");
    8. # Endif
    9. Return 0;
    10. }


I output the macro value.

 

Run the following command on the terminal:

 

    1. [] $ G ++-Dmy_mac=5./Dtest. C-o Dtest
    2. [] $./Dtest
    3. Hello-D. 5
    4. [] $

 

If the program has multiple macros, You can compile them like this.

 

    1. [] $ G ++-Dmac1=5 -Dmac2=6Soucefile. c

 

 

 

^ _ ^, Are you very excited ?? In this way, we do not need to modify macro variables in the code ..

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.