C ++,多重定义 [英] C++, multiple definition
问题描述
我需要定义一个包含环境变量(Linux,g ++)的常量。我更喜欢使用 string
,但是 std :: getenv
需要 * char
(这不是我的问题)。为了避免多个定义错误,我使用了 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 << "\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?
多重定义问题的典型答案是
- 分隔声明/实现
- 多个包含
在我的情况下,有没有办法将声明和实现分开?
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_H
并因此再次定义了 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 ++,多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!