gpt4 book ai didi

c++ - 使用 extern 时 gcc 重定位错误

转载 作者:行者123 更新时间:2023-11-30 05:25:56 24 4
gpt4 key购买 nike

我收到以下代码段的重定位错误。请有人帮我弄清楚这个问题。

A.hpp

namespace
{
class A
{
public:
A(const std::string&);
//Few Get() methods
private:
//Some private stuff
};
extern A objA;
}

A.cpp

#include<A.hpp>

const std::string str("FIXED STRING HERE");
A objA(str);

A::A(const std::string& Istring)
{
//Some data processing here
}

ClientCode.cpp

#include<A.hpp>



// Want to access A::get() here using objA;
objA.Get();

我收到以下错误:

relocation R_X86_64_PC32 against undefined symbol `(anonymous namespace)::str' can not be used when making a shared object; recompile with -fPIC
final link failed: Bad value
collect2: ld returned 1 exit status

另外,请有人告诉我这个外部对象的内存是什么时候分配的。我的主要目的是只拥有 A 类的单个对象,并在我包含 A.hpp 时跨多个文件使用它

最佳答案

A.hpp

namespace ABC
{
class A
{
public:
A(const std::string&);
//Few Get() methods
private:
//Some private stuff
};
extern A objA;
}

A.cpp

#include<A.hpp>
namespace ABC
{
const std::string str("FIXED STRING HERE");
A objA(str);

A::A(const std::string& Istring)
{
//Some data processing here
}
}

客户端代码.cpp

#include<A.hpp>
// Want to access A::get() here using objA;
ABC::objA.Get();

关于c++ - 使用 extern 时 gcc 重定位错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38037950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com