c++ - 在两个文件之间共享静态全局变量

标签 c++ compiler-errors linker

我有一个def.cc文件,它内置在静态库libdefine.a中:
def.h

#include<stdio.h>
#include <unistd.h>
 
 void testFunction();
 typedef struct _epoll_ctxt {
     int epfd;
     int last; 
 } epoll_ctxt;
定义文件
#include<stdio.h>
#include <unistd.h>
#include "def.h"

static int count = 0;
static epoll_ctxt g_epctxt;

 void testFunction() {
     g_epctxt.epfd = 5;
     printf("The epfd value is %d and val from  .h file", g_epctxt.epfd);
 }
我已经使用def.o创建了libdefine.a库
我想在test.cc(驱动程序函数)中使用变量 g_epctxt ,所以我将代码编写为
test.cc:
#include<stdio.h>
#include <unistd.h>
#include "def.h"

 extern epoll_ctxt g_epctxt;
 int main() {
     testFunction();
     g_epctxt.epfd = 8;
     printf("The epfd value is %d", g_epctxt.epfd);
     return 0;
 }
使用以下命令进行编译:gcc test.cc -L。 -定义
并出现以下错误:
/tmp/ccdr4Xi5.o:在“main”函数中:
test.cc:(.text+0x10):对'g_epctxt'的 undefined reference
test.cc:(.text+0x19):对'g_epctxt'的 undefined reference
collect2:ld返回1退出状态

有人可以帮助我,我在想什么。

最佳答案

def.cc中,以下声明表示具有内部链接的变量:

static epoll_ctxt g_epctxt;
C++标准section 6.6 §3.1:

A name having namespace scope has internal linkage if it is the name of

  • a variable, variable template, function, or function template that is explicitly declared static

此外,在section 6.6 §2.3中:

When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.


因此,当您在翻译单元(在本例中为static文件)中声明def.cc全局变量时,只能在同一翻译单元中引用它。具有内部链接的名称在标准中也称为TU-本地(翻译单元本地)。
基于section 6.6 §18,我们可以指出您的程序格式错误:

If a declaration that appears in one translation unit names a TU-local entity declared in another translation unit that is not a header unit, the program is ill-formed.


看起来您只想在所有其他翻译单元中使用g_epctxt变量的单个实例。因此,您希望变量具有外部链接。为此,您只需要在def.cc中定义变量而无需指定static:
// def.cc

// Global variables have external linkage by default
epoll_ctxt g_epctxt;
但是,最好在头文件中声明这种类型的extern变量(def.h)。这样,您不必在每次使用变量时都重新声明该变量,它还阐明了该变量被设计用于其他翻译单元:
// def.h
extern epoll_ctxt g_epctxt;
使用上面的extern声明,您应该从g_epctxt(和其他.cc文件)中删除现在多余的test.cc声明:
// test.cc

// This is redundant and should be removed
extern epoll_ctxt g_epctxt;
您也可以这样考虑解决方案:如果您想更改变量g_epctxt的名称或类型,是否只想在def.ccdef.hdef.c和所有其他.cc文件中使用它宣布。

关于c++ - 在两个文件之间共享静态全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64657994/

相关文章:

c++ - QVector 附加截断/舍入值

ios - React Native facebook iOS sdk 构建失败

python - 如何在使用 <iostream> 的 Python 中调用 C++ 代码

python - OpenCV-如何消除凸轮扫描仪中的凸度缺陷?

android - 库 com.google.android.gms :play-services-measurement-base is being requested by various other libraries at [[15. 0.0,

python - 为什么我在 'excpet'上收到语法错误?

python - 结构错误 : unpack requires a bytes object of length 2 on the second input of the program

c++ - 使用某些静态库时在开罗出现段错误

c - Mex无法正确链接,导致 "dyld: lazy symbol binding failed: Symbol not found: _mxGetNumberOfDimensions_700"

c++ - 检查字符串中的唯一字符