2.6

宏定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

#define PRINT_JOE

int main()
{
#ifdef PRINT_JOE
std::cout << "Joe\n"; // will be compiled since PRINT_JOE is defined
#endif

#ifdef PRINT_BOB
std::cout << "Bob\n"; // will be excluded since PRINT_BOB is not defined
#endif

return 0;
}
1
Joe

**#if 1 **和 **#if 0 **

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
std::cout << "Joe\n";

#if 0 // Don't compile anything starting here
std::cout << "Bob\n";
std::cout << "Steve\n";
#endif // until this point

return 0;
}
1
Joe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
std::cout << "Joe\n";

#if 1 // always true, so the following code will be compiled
std::cout << "Bob\n";
/* Some
* multi-line
* comment here
*/
std::cout << "Steve\n";
#endif

return 0;
}
1
2
3
Joe
Bob
Steve

为了防止文件头中的函数被多次包含,被重写而产生错误,我们可以用:

1
2
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE

比如你有一个add.h

你就使用:

1
2
#ifndef ADD_H
#define ADD_H

但是现在一般都是使用

1
#pragma once