[英]C++, multiple definition
I need to define a constant containing an environment variable (Linux, g++). 我需要定义一个包含环境变量(Linux,g ++)的常量。 I would prefer to use
string
, but std::getenv
needs *char
(this is not yet my question). 我更喜欢使用
string
,但是std::getenv
需要*char
(这不是我的问题)。 To avoid the multiple definition error I used the define
workaround, but it is not enough. 为了避免多定义错误,我使用了
define
解决方法,但这还不够。 The program is simple: DataLocation.hpp
程序很简单:
DataLocation.hpp
#ifndef HEADER_DATALOCATION_H
#define HEADER_DATALOCATION_H
#include <string>
using namespace std;
const char* ENV_APPL_ROOT = "APPL_ROOT";
[...]
#endif
And DataLocation.cpp
: 和
DataLocation.cpp
:
#include <string>
#include <cstdlib>
#include "DataLocation.hpp"
using namespace std;
// Private members
DataLocation::DataLocation()
{
rootLocation = std::getenv(ENV_APPL_ROOT);
}
[...]
And a test programm, Test.cpp
还有一个测试程序
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";
}
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?
怎么了?
The typical answers to the multiple definition question are either 多重定义问题的典型答案是
Is there a way to separate declaration and implementation in my case? 在我的情况下,有没有办法将声明和实现分开?
Edit 1 编辑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.
在所引用问题的解决方案中,我看不到如何解决我的问题。
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 . 一旦从DataLocation.cpp(其中它找到
HEADER_DATALOCATION_H
尚未定义和因此限定ENV_APPL_ROOT
从Test.cpp的),并且一旦(它agains发现HEADER_DATALOCATION_H
尚未定义和因此限定ENV_APPL_ROOT
一次。)的“报头保护”仅保护的报头文件被多次包含在同一编译单元中 。
You need: 你需要:
extern const char* ENV_APPL_ROOT;
in the header file, and 在头文件中,以及
const char* ENV_APPL_ROOT = "APPL_ROOT";
in one .cpp file. 在一个.cpp文件中。
Use 采用
extern const char* ENV_APPL_ROOT;
in the header file, and place 在头文件中,并放置
const char* ENV_APPL_ROOT = "APPL_ROOT";
in one particular translation unit (eg DataLocation.cpp
). 在一个特定的转换单元(例如
DataLocation.cpp
)中。
This should fix it. 这应该解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.