【问题标题】:One header file in multipe cpp files: Multiple definition [duplicate]多个cpp文件中的一个头文件:多个定义[重复]
【发布时间】:2021-10-16 05:39:40
【问题描述】:

我正在尝试访问多个 C++ 文件中的一个头文件。头文件定义如下:

#ifndef UTILS
#define UTILS

void toUpper(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = toupper(str.at(i));
    }
}

void toLower(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = tolower(str.at(i));
    }
}


#endif // UTILS

当我编译代码时,我收到以下错误:

据我所知,这不应该返回多个定义,因为我限制代码被多次定义。我还尝试使用预编译指令“#pragma once”

【问题讨论】:

  • 请提供您省略的代码(至少一部分)。没有它,我们就无法为您提供帮助。
  • @AnoopRana 我添加了代码
  • 您使用的包含保护可以防止某些形式的多定义错误,但不是全部。它可以防止Utils.hpp 的多个副本出现在同一个翻译单元中。但是,如果Utils.hpp 的多个副本出现在多个不同的翻译单元中,这仍然违反了单一定义规则,并且包含保护没有任何作用来防止这种情况发生。 (实际上,您不想要阻止这种情况,因为您的目标是在多个源文件中使用这些函数。)解决方法是,如下所述,inline 关键字。
  • 头文件内容错误导致问题。清理一下就解决了。这与答案中的第二个选项相匹配,不定义代码两次是关键。 reinclusion guard 和 pragma 都不会阻止它。使用内联解决/隐藏问题,但不是唯一的解决方案。我不同意我的欺骗提议不适用。 @jxh
  • @Yunnosch 在这种情况下,更重要的是解释如何正确定义内联函数,而不是建议用户永远不要使用它们。

标签: c++ one-definition-rule inline-functions


【解决方案1】:

这个问题有两种解决方案。

解决方案 1

您可以在函数前添加关键字inline

myfile.h

#ifndef UTILS
#define UTILS

inline void toUpper(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = toupper(str.at(i));
    }
}

inline void toLower(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = tolower(str.at(i));
    }
}


#endif // UTILS

现在您可以将此标头包含在不同的文件中,而不会出现上述错误。

解决方案 2

您可以创建一个单独的 .cpp 文件并将定义放在那里。这看起来像:

myfile.h

#ifndef UTILS
#define UTILS

//just declarations here
void toUpper(string &str);    //note no inline keyword needed here

void toLower(string &str);    //note no inline keyword needed here

#endif // UTILS

myfile.cpp

#include "myheader.h"
void toUpper(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = toupper(str.at(i));
    }
}

void toLower(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = tolower(str.at(i));
    }
}


【讨论】:

  • 正如我所料,我更喜欢它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
相关资源
最近更新 更多