gpt4 book ai didi

c++ - extern "C"extern 变量在 C++ 程序中作为类变量寻求..如何声明它?

转载 作者:行者123 更新时间:2023-12-04 13:52:39 32 4
gpt4 key购买 nike

我在下面有一个代码。它是由 qemu 程序(一个 C 程序)使用 dlopen 加载的动态共享库的一部分。

extern "C" {
extern uint64_t host_virt_offset;
}

int Driver::CallSetBareMetalMode( uint64_t * args_ptr)
{
dbg_enter();

(... some codes ..)

baremetal_axpu_es = (struct es_t *)(args_ptr[0] + host_virt_offset); // line a
baremetal_axpu_regs = (struct reg_csr_t *)(args_ptr[1] + host_virt_offset); // line b

dbg_leave();
return 0;
}
因为变量 host_virt_offset 是在 qemu(一个 C 程序)中定义的,所以我认为它可以在这个共享库中使用没有问题。但是当我运行它时,发生错误,当我使用调试器检查它时,我发现代码正在寻找 Driver::host_virt_offset 而不是全局(和外部)变量 host_virt_offset 。我通过下面那条线附近知道这一点。
(gdb) print host_virt_offset
Missing ELF symbol "AXPU::host_virt_offset".
我尝试在 a,b 行中使用 ::host_virt_offset 但它无法编译。我应该如何声明和使用变量 host_virt_offset?
添加:(我有一段时间无法连接到 stackoverflow)我制作了一个可重现的程序。在这里使用我使用的方法可以正常工作。所以还有其他事情。 '
<< main.c >>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

uint64_t var_from_qemu = 0x12345678;

int main(void)
{
void * dlh = dlopen("./libbar.so", RTLD_NOW);
if (!dlh) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
void (*bar)(void) = dlsym(dlh,"bar");
if (!bar) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
bar();
return 0;
}
< > <-- 共享库
#include <stdint.h>
#include <stdio.h>

extern "C" {
extern uint64_t var_from_qemu;
}

class BC;

class BC {
public:
void bar(void);
BC();
~BC();
};

BC::BC()
{
}

BC::~BC()
{
}

void BC::bar(void)
{
printf("class function : var_from_qemu = %lx\n", var_from_qemu);
}

extern "C" {
void bar(void)
{
printf("global function : var_from_qemu = %lx\n", var_from_qemu);
BC tmp;
tmp.bar();
}
}
<<结果>>
$ g++ bar.cpp -Wall -fpic -shared -g -o libbar.so
$ gcc main.c -o main -g -ldl -rdynamic
$ main
global function : var_from_qemu = 12345678
class function : var_from_qemu = 12345678

最佳答案

extern "C"在声明变量时没有区别,它只对函数重要。
原因是 C++ 中的函数可以重叠,但变量不能。
例如:

#include <iostream>
using namespace std;
extern "C" {
int n1 = 1;

}
int n2 =2;
int main()
{
cout<<n1<<endl<<n2<<endl;
return 0;
}
在上面的代码中, n1n2访问相同。

关于c++ - extern "C"extern 变量在 C++ 程序中作为类变量寻求..如何声明它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67884953/

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