Macro expand in C programming language

Source: Internet
Author: User

Just yesterday, a question came into my mind:

When a C compiler preprocess the macro define?

 

So comes a test in Ubuntu 10.10

Gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5

 

// Header file

# Ifndef TEST_H __

# Define TEST_H __

 

# Define and +

 

# Endif

 

 

// Source file

# Include "test. h"

 

# Define ADD (X) (X and X)

 

Void f (){

ADD (X );

Return 0;

}

 

Int main (int argc, char ** argv ){

Int I = 20;

F (I );

Return 0;

}

// End of source file

 

Using the-E Option in GCC to preprocess the test. C, the result is

#1 "test. c"

#1 "<built-in>"

#1 "<command-line>"

#1 "test. c"

#1 "test. H" 1

#2 "test. c" 2

 

 

 

Void F (){

(X and X );

Return 0;

}

 

Int main (INT argc, char ** argv ){

Int I = 20;

F (I );

Return 0;

}

 

// End of the process

 

If we exchange the macro define (and) and (ADD) in header file and source file

We can get the following result after preprocessing.

 

#1 "test. c"

#1 "<built-in>"

#1 "<command-line>"

#1 "test. c"

#1 "test. h" 1

#2 "test. c" 2

 

 

 

Void f (){

(X + X );

Return 0;

}

 

Int main (int argc, char ** argv ){

Int I = 20;

F (I );

Return 0;

}

 

// End of the process

 

When I defined all macro in two different header file,

The macro cocould expand correctly, whatever order

Header file.

 

So, I think an answer cocould come out:

We 'd better define macro in header file.

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.