Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;,多重定义_C++_Compiler Errors - Fatal编程技术网

C++ C++;,多重定义

C++ C++;,多重定义,c++,compiler-errors,C++,Compiler Errors,我需要定义一个包含环境变量的常量(Linux,g++)。我更喜欢使用string,但是std::getenv需要*char(这还不是我的问题)。为了避免多重定义错误,我使用了define变通方法,但这还不够。程序很简单:DataLocation.hpp #ifndef HEADER_DATALOCATION_H #define HEADER_DATALOCATION_H #include <string> using namespace std; const char* ENV

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

#ifndef HEADER_DATALOCATION_H
#define HEADER_DATALOCATION_H

#include <string>

using namespace std;

const char* ENV_APPL_ROOT = "APPL_ROOT";

[...]

#endif
和一个测试程序,
test.cpp

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

using namespace std;

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

  cout << "Root: " << s << "\n";
}
在我的代码中没有第二个定义,我保护头不被调用两次。怎么了

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

  • 分开申报/执行
  • 倍数包括
在我的情况下,有没有办法将声明和实现分开

编辑1

这个问题与我的问题无关,因为我的问题指的是一个常数。在所引用问题的解答中,我看不出如何解决我的问题。

使用

extern const char* ENV_APPL_ROOT;
在头文件中,并放置

const char* ENV_APPL_ROOT = "APPL_ROOT";
在一个特定的翻译单元中(例如,
DataLocation.cpp

这应该可以解决它。

使用

extern const char* ENV_APPL_ROOT;
在头文件中,并放置

const char* ENV_APPL_ROOT = "APPL_ROOT";
在一个特定的翻译单元中(例如,
DataLocation.cpp


这应该可以解决问题。

您将包含两次标题。一次来自DataLocation.cpp(它发现
HEADER\u DataLocation\u H
尚未定义,因此再次定义了
ENV\u APPL\u ROOT
),一次来自Test.cpp(它再次发现
HEADER\u DataLocation\u H
尚未定义,因此再次定义了
ENV\u APPL\u ROOT
)“头保护”仅保护在同一编译单元中多次包含的头文件

你需要:

extern const char* ENV_APPL_ROOT;
在头文件中,以及

const char* ENV_APPL_ROOT = "APPL_ROOT";

在一个.cpp文件中。

包含两次标题。一次来自DataLocation.cpp(它发现
HEADER\u DataLocation\u H
尚未定义,因此再次定义了
ENV\u APPL\u ROOT
),一次来自Test.cpp(它再次发现
HEADER\u DataLocation\u H
尚未定义,因此再次定义了
ENV\u APPL\u ROOT
)“头保护”仅保护在同一编译单元中多次包含的头文件

你需要:

extern const char* ENV_APPL_ROOT;
在头文件中,以及

const char* ENV_APPL_ROOT = "APPL_ROOT";
在一个.cpp文件中。

它定义了两次—在包含.hpp文件的每个.cpp文件中定义了一次。它的可能副本定义了两次—在包含.hpp文件的每个.cpp文件中定义了一次可能的副本