gpt4 book ai didi

c++ - 包含 Guards 和#ifndef#define 预处理语句

转载 作者:行者123 更新时间:2023-11-30 04:11:35 25 4
gpt4 key购买 nike

如果我执行以下操作:

dConst.hpp

const int POWER_LEVEL = 9001;

genPower.hpp

#include "dConst.hpp"

#ifndef GENPOWER_HPP
#define GENPOWER_HPP

const int GENERATOR[1] = { POWER_LEVEL };

#endif

对于任何使用生成器数组常量的代码,我最终都会遇到链接器错误。

但是,如果我用代码块切换 #include "dConst.hpp":

#ifndef GENPOWER_HPP
#define GENPOWER_HPP

有效...

我是否滥用了 #ifndef 的功能?

最佳答案

没有充分利用#ifndef 的力量。

您的dConst.hpp 文件需要包含守卫。否则,如果它包含在一个翻译单元中的多个文件中,将会导致问题(您看到的确切问题)。

编辑:我还将在文件顶部的 genPower.hpp 中放置您的 include 守卫,在您的 include 语句之前。

关于c++ - 包含 Guards 和#ifndef#define 预处理语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179760/

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