gpt4 book ai didi

c++ - 如何使用#error 指令为用户提供指向有用信息的指针?

转载 作者:太空宇宙 更新时间:2023-11-04 14:02:04 25 4
gpt4 key购买 nike

假设我有一个像下面这样的文件

主文件.cpp

 #include "stdafx.h"
#include <stdlib.h>
#include "Myfile.h"
#ifdef _MYFILE
#error Myfile.h to be included. Please refer Ream Me at C:\ReadMe
#endif


int _tmain(int argc, _TCHAR* argv[])
{
system("pause");
return 0;
}

Myfile.h

#pragma once
#undef _MYFILE
#define MYFILE

我的目标是提供额外的信息(“请引用 ....”),以防丢失某些东西(路径中未包含/找不到 MyFile.h)。

我如何使用第三方库(如 Boost)处理此问题?在这种情况下,我无法控制 Boost 并且我无法处理 _MYFILE 的定义:那么如何抛出错误?

伪代码

#include "boost/boost.h"
#if (boost is not included || directory path is not set || boost .h file not found)
#error: Set boost path and compile again
#endif

最佳答案

在 C/C++ 代码中不可能做你想做的事。输入 #include "myfile.h" 后,编译器将查找该文件并在找不到时抛出错误。

您还滥用了 #ifndef ... #error ... #endif。有些人用它来跟踪 header 依赖性;假设您有一个 header messages.h,它需要 header mytypes.h。通常你只需要这样写:

//文件 mytypes.h

#ifndef MYTYPES_H
#define MYTYPES_H

typedef unsigned char UINT8;
// ...

#endif

//文件messages.h

#ifndef MESSAGES_H
#define MESSAGES_H

#include "mytypes.h"

// ...

#endif

但是你也可以这样写messages.h:

#ifndef MESSAGES_H
#define MESSAGES_H

#ifndef MYTYPES_H
#error I need mytypes.h to compile!
#endif

#endif

但是,为您依赖的所有 header 插入#errors,然后在需要您的 header 的所有源文件中一遍又一遍地包含这些依赖项,很快就会变得很麻烦。所以在大多数情况下,第一种方法是可行的方法。

您还需要决定要使用哪种类型的包含防护。如果您已经在使用#pragma once,请不要#define MYFILE。选择一个并坚持下去。 (请记住 #pragma once 是非标准的)。

最后但并非最不重要的一点是:如果您真的需要对用户友好,您将需要使用您的构建系统来验证是否安装了所有额外的库并且它们的 header 可用。我的猜测是您正在使用 Visual Studio 的 native 生成器。我不知道那个,但我读到它有预构建操作,所以也许可以定义一个通过一些本地 visual studio 调用或简单地通过运行项目中包含的批处理文件来验证提升位置的操作。

关于c++ - 如何使用#error 指令为用户提供指向有用信息的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18894658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com