我有一个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.cc
和def.h
或def.c
和所有其他.cc文件中使用它宣布。
关于c++ - 在两个文件之间共享静态全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64657994/