C++,多重定义

C++, multiple definition(C++,多重定义)

本文介绍了C++,多重定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个包含环境变量的常量(Linux、g++).我更喜欢使用 string,但 std::getenv 需要 *char(这还不是我的问题).为了避免 multiple definition 错误,我使用了 define 解决方法,但这还不够.程序很简单:DataLocation.hpp

I need to define a constant containing an environment variable (Linux, g++). I would prefer to use string, but std::getenv needs *char (this is not yet my question). To avoid the multiple definition error I used the define workaround, but it is not enough. The program is simple: DataLocation.hpp

#ifndef HEADER_DATALOCATION_H
#define HEADER_DATALOCATION_H

#include <string>

using namespace std;

const char* ENV_APPL_ROOT = "APPL_ROOT";

[...]

#endif

DataLocation.cpp:

#include <string>
#include <cstdlib>
#include "DataLocation.hpp"

using namespace std;

// Private members
DataLocation::DataLocation()
{
  rootLocation = std::getenv(ENV_APPL_ROOT);
}

[...]

还有一个测试程序,Test.cpp

#include "DataLocation.hpp"
#include <iostream>

using namespace std;

int main() {
  DataLocation *dl;
  dl = DataLocation::getInstance();
  auto s = dl->getRootLocation();

  cout << "Root: " << s << "
";
}

但是编译,我得到以下错误:

But compiling, I get the following error:

/tmp/ccxX0RFN.o:(.data+0x0): multiple definition of `ENV_APPL_ROOT'
DataLocation.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [Test] Error 1

在我的代码中没有第二个定义,我保护标头不被调用两次.怎么了?

In my code there is no second definition, and I protect the header from being called twice. What is wrong?

多重定义问题的典型答案是

  • 分离声明/实现
  • 多个包含

在我的情况下,有没有办法将声明和实现分开?

Is there a way to separate declaration and implementation in my case?

编辑 1

这个问题没有链接到这个问题,因为我的指的是一个常数.在引用问题的解决方案中,我没有看到如何解决我的问题.

This question is not linked to this question because mine refers to a constant. In the solution of the cited question I do not see how to solve my problem.

推荐答案

您将标题包含两次.一次来自 DataLocation.cpp(它发现 HEADER_DATALOCATION_H 尚未定义,因此定义了 ENV_APPL_ROOT),一次来自 Test.cpp(它再次发现 HEADER_DATALOCATION_Hcode> 尚未定义,因此再次定义 ENV_APPL_ROOT.)头文件保护"仅保护在同一编译单元中多次包含的头文件.

You are including the header twice. Once from DataLocation.cpp (where it finds HEADER_DATALOCATION_H not yet defined and thus defines ENV_APPL_ROOT), and once from Test.cpp (where it agains finds HEADER_DATALOCATION_H not yet defined and thus defines ENV_APPL_ROOT again.) The "header protection" only protects a header file being included multiple times in the same compilation unit.

您需要:

extern const char* ENV_APPL_ROOT;

在头文件中,和

const char* ENV_APPL_ROOT = "APPL_ROOT";

在一个 .cpp 文件中.

in one .cpp file.

这篇关于C++,多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++,多重定义

基础教程推荐