pragma一次或ifndef定义endif

时间:2016-10-05 14:40:30

标签: c++ pragma include-guards

在头文件中我们使用预处理器制作包含保护,以便避免包含多个头文件,所以我们写道:

// mytest.h

#ifndef MY_TEST_H
#define MY_TEST_H

// code here
int foo() { return 0; }

#endif

// main.cpp

#define MY_TEST_H // example unintentionally we define it or it is defined in other header file that is included here in main right before inclusion of mytest.h

#include <iostream>
#include "mytst.h"

int main()
{
    std::coutcout << foo() << std::endl; // foo(): undeclared identifer
    return 0;
}
  • 上面的一些缺点:如果在我们的源代码中有一个与MY_TEST_H同名的宏定义,则在mytest.h中包含mytest.h将在头文件mytest.h中的预处理器失败时发出,因此它的内容将不包括在内因此foo是未声明的标识符!

实现上述目的的另一种方法(避免多个头包含)并避免预处理器包含保护的缺点是在我们的头中使用pragma:

#pragma once

问题:pragma比包含警卫更强大吗?如果是这样,为什么人们还在使用包容警卫?

0 个答案:

没有答案
相关问题