条件编译,可以用来有选择地对部分程序源代码进行编译
#ifdef DEBUG
cerr <<"Variable x = " << x << endl;
#endif
#ifdef DEBUG 之前已经定义了符号常量 DEBUG,则会对程序中的 cerr 语句进行编译。 #if 0 语句注释掉程序的一部分
#include <iostream>
using namespace std;
#define DEBUG
#define MIN(a,b) (((a)<(b)) ? a : b)
int main ()
{
int i, j;
i = 100;
j = 30;
#ifdef DEBUG
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
/* 这是注释部分 */
cout << MKSTR(HELLO C++) << endl;
#endif
cout <<"The minimum is " << MIN(i, j) << endl;
#ifdef DEBUG
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
结果
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function
2.# 和 ## 运算符
运算符会把 replacement-text 令牌转换为用引号引起来的字符串。
#define MKSTR( x ) #x
int main ()
{
cout << MKSTR(HELLO C++) << endl;
//转换成cout << "HELLO C++" << endl;
return 0;
}
##连接两个令牌
#define concat(a, b) a ## b
cout << concat(x, y);//cout << xy;
预定义宏
LINE 这会在程序编译时包含当前行号。
FILE 这会在程序编译时包含当前文件名。
DATE 这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期。
TIME 这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。
cout << "Value of LINE : " << LINE << endl;
C++ 多线程
两种类型的多任务处理:基于进程和基于线程。
基于进程的多任务处理是程序的并发执行。
基于线程的多任务处理是同一程序的片段的并发执行。
创建线程
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)创建一个新的线程,并让它可执行,函数返回 0,若返回值不为 0 则说明创建线程失败
终止线程
pthread_exit (status)
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
struct thread_data{
int thread_id;
char *message;
};
void *PrintHello(void *threadarg)
{
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
cout << "Thread ID : " << my_data->thread_id ;
cout << " Message : " << my_data->message << endl;
pthread_exit(NULL);
}
int main ()
{
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout <<"main() : creating thread, " << i << endl;
td[i].thread_id = i;
td[i].message = (char*)"This is message";
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)&td[i]);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
连接和分离线程
pthread_join (threadid, status)
pthread_detach (threadid)