【问题标题】:Accessing Global variable across files跨文件访问全局变量
【发布时间】:2021-10-19 08:51:18
【问题描述】:

我需要从d.cpp 访问c.cpp 中的m[]。数组m[] 是命名空间内CD 的成员,并在该类内的c.h 中声明。所以我在文件c.h 的同一类CD 中声明了一个静态数组s[]。在c.cpp中实例化它,并使用一个函数将原始数组m[]的元素复制到静态数组s[]。然后,我在需要访问它的d.cpp#include "c.h"

c.h

namespace k{
class CD {
string m[10];
static string s[10];
}}

c.cpp

#include "c.h"
namespace k{
string CD::s[10] = {"q"}
}

d.cpp

#include "c.h"
void func(){
string n = k::CD::s[0];    
}

但我收到一条错误消息,提示未定义对 k::CD::s 的引用。

我在这里做错了吗?还是有其他方法可以做到这一点?

【问题讨论】:

  • 使用您显示的代码,您应该会遇到更多错误。请了解如何创建minimal reproducible example。也请花一些时间阅读the help pages,阅读SO tour,阅读How to Ask,以及this question checklist。最后请学习如何edit您的问题以改进它们。
  • 哦,还请告诉我们您是如何构建该程序的。如果您在终端中执行此操作,请向我们展示您使用的确切命令。如果您使用 IDE,请告诉我们您是如何设置项目的,以及哪些文件被列为项目的一部分。如果有任何文本构建输出,则将其复制粘贴到问题中。
  • #include c.h => #include "c.h"
  • "所以我在文件CD 的同一类中声明了一个静态数组s[] c.h" - 你让它听起来像你这样做是为了得到访问m - 但单个实例s 和所有m:s 未连接。如果我的回答不能解决您的问题,请澄清您的问题。

标签: c++ arrays static global-variables


【解决方案1】:

一些注意事项:

c.h

#ifndef C_H_HEADER_GUARD // add header guard
#define C_H_HEADER_GUARD

#include <string> // you need this header

namespace k {

class CD {
    // string is in the "std" namespace, so:
    std::string m[10];      // note that this is private!

// "s" can't be private since you want to access it outside the class, in `func()`:
public:
    static std::string s[10];
}; // class definitions need to end with ;

} // namespace k

#endif

c.cpp

#include "c.h" // enclose the header with quotation marks

namespace k {
using namespace std;      // in here it's ok to use namespace std:
string CD::s[10] = {"q"}; // missing ;
} // namespace k

d.cpp

#include "c.h" // again, quotation marks

void func() {
    std::string n = k::CD::s[0]; // missing std::
}

现在,这会将两个翻译单元编译为 c.od.o,您可以在稍后与包含 main 的 TU 链接时使用它们。

g++ -c c.cpp d.cpp -Wall -Wextra -pedantic -pedantic-errors

由于d.cpp 没有d.h 来声明函数func,因此您需要声明要在哪里使用它。不好,但是:

void func();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多