在源代码中是否可以知道是否包含标题?
这是我需要的一个例子:
#include<iostream>
using namespace std;
int main()
{
char headname[4];
cout<<"Enter a header name : ";
cin>>headname;
#ifdef headname
cout<<headname<<" Defined"<<endl;
#else
cout<<headname<<" Not defined"<<endl;
#endif
return 0;
}
例如,如果我输入“iostream”,则输出应为“iostream Defined”。
答案 0 :(得分:3)
是。标题通常使用包含警戒,例如:
#ifndef MY_HEADER_INCLUDED
#define MY_HEADER_INCLUDED
// [...]
#endif
在我的Gentoo Linux / GCC系统上,看到iostream标题,我看到了:
#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1
因此您可以查看_GLIBCXX_IOSTREAM
。如果您没有使用GCC,请打开iostream
标头文件,看看他们可能定义了哪些宏。
还应该指出cout
属于iostream
标头,所以当_GLIBCXX_IOSTREAM
(在我的情况下)没有定义时,代码也将无法编译。但您可以使用printf()
进行测试。
答案 1 :(得分:1)
当然可以:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main(void) {
std::vector<std::string> includes;
includes.push_back("iostream");
includes.push_back("vector");
includes.push_back("string");
includes.push_back("algorithm");
std::string user_input;
std::cout << "Enter a header name: ";
std::cin >> user_input;
if ( std::find(includes.begin(), includes.end(), user_input) !=
includes.end() ) {
std::cout << user_input << " is included." << std::endl;
} else {
std::cout << user_input << " is not included." << std::endl;
}
return 0;
}
输出:
paul@local:~/src/cpp/scratch$ ./incl
Enter a header name: iostream
iostream is included.
paul@local:~/src/cpp/scratch$ ./incl
Enter a header name: map
map is not included.
paul@local:~/src/cpp/scratch$
答案 2 :(得分:0)
首先,检查标题,“在运行时”和“在编译时”没有什么不同,因为#include
在编译时与任何#ifdef
一起执行。 #include
基本上会在.cpp文件的顶部复制粘贴标头。 Razvan Cojocaru指出,您可以使用#ifdef
检查天气_GLIBCXX_IOSTREAM
是否已定义。以下是可以使用它的一个小例子:
class Flagger
{
typedef unsigned long ulong;
public:
Flagger (ulong flags = 0) : f(flags) { ; }
Flagger (const Flagger& cpy) : f(cpy.f) { ; }
void clear (ulong flags) { f &= ~flags; }
void set (ulong flags) { f |= flags; }
void toggle (ulong flags) { f ^= flags; }
bool get (ulong flags) { return f & flags; }
#ifdef _GLIBCXX_OSTREAM
friend std::ostream& operator << (std::ostream &out, const Flagger& f)
{ /* print it how you want it*/ }
#endif
private:
ulong f;
};
然而,这可能是个坏主意,原因如下:
所以基本上,是的,可能,但不实用。特别适合长期维护。好处并不比危险大。只需自己包含有问题的图书馆。
正如其他人所说,如果我们知道你的最终结果是什么,将会有所帮助。您计划使用此功能的地方最有可能提供更好的解决方案。
答案 3 :(得分:-1)
是的,快速破解是:
您需要做的就是转到源代码头文件。并通过 -
访问任何成员(任何在头文件源代码中定义的常量) cout<<ACCESSED_MEMBER
现在编译并运行程序,如果你在控制台上打印出来,那么祝贺,该文件已成功包含在您的代码中。
注意:1 查找标题的特定源文件。你可以在终端上输入
locate <header_file_name>
您将获得文件的位置。现在通过在vi或nano或gedit或您选择的任何编辑器中打开它来检查任何成员。
注意:2 如果此标头文件不属于您,请勿对此进行任何更改。