【发布时间】:2020-11-03 06:51:40
【问题描述】:
我有一个构建到静态库 libdefine.a 中的 def.cc 文件:
def.h
#include<stdio.h>
#include <unistd.h>
void testFunction();
typedef struct _epoll_ctxt {
int epfd;
int last;
} epoll_ctxt;
def.cc
#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。 -ldefine 并得到以下错误:
/tmp/ccdr4Xi5.o:在函数“主”中: test.cc:(.text+0x10): 对“g_epctxt”的未定义引用 test.cc:(.text+0x19): 对“g_epctxt”的未定义引用 collect2: ld 返回 1 个退出状态谁能帮我看看我错过了什么。
【问题讨论】:
-
尝试谷歌变量声明中的
static是什么意思。 -
@MikeCAT,我已经有一个很大的代码库,所以我简化了问题并输入了示例格式。我想在另一个 .cc 文件中使用这些全局变量
-
不暴露全局变量,不如封装需要的行为,然后暴露接口?
-
为什么同时标记 C 和 C++?它们是两种不同的语言
-
“静态但全局”就像说“猫但狗”或“红色但绿色”。使用
static的真正目的是阻止变量全局暴露。所以实际的问题是你的程序设计。请改用 setter/getter 函数。
标签: c++ compiler-errors linker