【发布时间】:2017-03-14 11:45:03
【问题描述】:
我以前使用过 extern 关键字,但现在我遇到了一个非常奇怪的问题。
首先我有一个包含外部变量声明的 common.hh 文件:
//some extern declarations
extern const char* PATH;
在我的 main.cc 中,我执行以下操作(暂时忽略 cout):
#include "common.hh"
const char* PATH;
int main(const int argc, const char* argv[]){
PATH = somePath.c_str();
//std::cout << PATH << std::endl; //will print the correct path
//std::cout << std::string(PATH) << std::endl; //will fix the problem occuring later
//some function calls to other files where PATH is used
//... somePath still in scope ...
//... somePath is about to be destroyed
}
现在我有其他文件 Other.hh 和 Other.cc 出现问题: 首先是我的Other.hh
#include "common.hh"
//function declarations and some other stuff
在Other.cc中出现访问PATH的问题:
#include "Other.hh"
void someFunction(...){
std::cout << PATH << std::endl; //When accessing PATH here again it prints garbage
在我的文件 Other.cc 中,我需要 main.cc 中定义的 const char* PATH,但由于某种原因 PATH 已更改。如果我在我的 main.cc 中的某处执行 std::string(PATH) ,整个问题就解决了,如上面的 cout 所示。我不明白出了什么问题,我所有的其他外部变量都可以正常工作。
编辑: 问题暂时解决了。我刚刚在 main.cc 中做了以下操作:
std::string tmp = somePath;
PATH = tmp.c_str();
我只是不明白为什么这可以解决问题,因为理论上 tmp 和 somePath 应该具有相同的范围,并且在 other.cc 中的函数调用执行之前不应该被销毁。换句话说:我在 other.cc 中的函数调用是在somePath 的范围结束之前。
【问题讨论】:
-
请提供一个最小的、完整的、可验证的示例 (stackoverflow.com/help/mcve)。
标签: c++ pointers char constants extern