当前位置:网站首页>C language: how to give an alias to a global variable?
C language: how to give an alias to a global variable?
2022-06-13 07:25:00 【qq_ forty-three million four hundred and seventy-nine thousand 】
High quality resource sharing
Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
---|---|---|
🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
do person : Doug ,10+ Embedded development veteran , Focus on :C/C++、 The embedded 、Linux.
Pay attention to the official account below. , reply 【 Books 】, obtain Linux、 Classic books in embedded field ; reply 【PDF】, Get all original articles ( PDF Format ).
Catalog
Catalog * What's an alias ?
The experience of others , Our steps !
What's an alias ?
stay stackoverflow
I saw an interesting topic on : How to set an alias for a variable ?(How to assign to a variable an alias?
)
The so-called variable alias , Different identifiers pass through , To represent the same variable .
We know , Variable names are for programmers .
In the eyes of the compiler , All variables become addresses .
Please note that : The alias discussed here , Just reference the same variable through different identifiers .
And strong sign 、 Weak symbols don't matter , That's another topic .
In the above post , The author's first thought is to define , Rename the variable .
The way to do it , It will be in the preprocessing phase before compilation , Replace macro identifier with variable identifier .
In the answers replied by netizens , Most of them are implemented through pointers : Let different identifiers point to the same variable .
Anyway? , This is also an alias .
however , These answers have one limitation : These codes must be compiled together to , Otherwise, there may be an error message that the symbol cannot be found .
Plug in programming is very popular now , If the developer wants to reference the variables in the main program through a variable alias in the plug-in , How to deal with this ?
This article provides two ways to achieve this , And through two simple example code to demonstrate .
At the end of the article, there is the download address of the sample code .
Method 1: Reverse registration
I've been in touch with some before CodeSys
Code for , The code quality inside is really very high , Especially the software architecture design .
Legend has it that :CodySys It's from the industrial control industry Android.
There is an idea of reverse registration , It can be used for variable aliases .
There are... In the sample code 2 File :main.c
and plugin.c
.
main.c
A global variable array is defined in , Compile into executable program main
.
plugin.c
Used by an alias in main.c
Global variable in .
plugin.c
Compiled into a dynamic link library , By executable program main
Dynamic loading (dlopen
).
stay plugin.c
in , Provide a function func_init
, When the dynamic library is main
dlopen
after , This function is called , And pass the address of the real global variable through the parameter .
In this case , In the plug-in, you can use real variables through an alias ( such as : Change the value of the variable ).
Essentially , This is still a reference through a pointer .
Just use the idea of dynamic registration , Isolate the binding relationship between pointer and variable in time and space .
plugin.c Source file
#include
int *alias_data = NULL;
void func\_init(int *data)
{
printf("libplugin.so: func\_init is called. \n");
alias_data = data;
}
void func\_stage1(void)
{
printf("libplugin.so: func\_stage1 is called. \n");
if (alias_data)
{
alias_data[0] = 100;
alias_data[1] = 200;
}
}
main.c Source file
#include
#include
#include
// defined in libplugin.so
typedef void (*pfunc\_init)(int *);
typedef void (*pfunc\_stage1)(void);
int data[100] = { 0 };
void main(void)
{
data[0] = 10;
data[1] = 20;
printf("data[0] = %d \n", data[0]);
printf("data[1] = %d \n", data[1]);
// open libplugin.so
void *handle = dlopen("./libplugin.so", RTLD_NOW);
if (!handle)
{
printf("dlopen failed. \n");
return;
}
// get and call init function in libplugin.so
pfunc_init func_init = (pfunc_init) dlsym(handle, "func\_init");
if (!func_init)
{
printf("get func\_init failed. \n");
return;
}
func\_init(data);
// get and call routine function in libplugin.so
pfunc_stage1 func_stage1 = (pfunc_stage1) dlsym(handle, "func\_stage1");
if (!func_stage1)
{
printf("get func\_stage1 failed. \n");
return;
}
func\_stage1();
printf("data[0] = %d \n", data[0]);
printf("data[1] = %d \n", data[1]);
return;
}
The compilation instructions are as follows :
gcc -m32 -fPIC --shared plugin.c -o libplugin.so
gcc -m32 -o main main.c -ldl
Execution results :
data[0] = 10
data[1] = 20
libplugin.so: func_init is called.
libplugin.so: func_stage1 is called.
data[0] = 100
data[1] = 200
You can take a look at the symbol table of the dynamic link library :
readelf -s libplugin.so | grep data
You can see alias_data
identifier , And is the global variable defined in this document .
【 About author 】
Master : Doug , More than ten years of embedded development veteran , Focus on embedded systems + Linux field , Yes Single chip microcomputer 、 Have done Smart home 、 Studied PLC and Industrial robot , Project development experience is very rich .
His articles mainly include C/C++、Linux operating system 、 The Internet of things 、 MCU and embedded .
whole 、 The perspective-taking , Summarize the article from the perspective of readers .
Every output , It's not just dry goods , It also guides you to think deeply step by step , Improve yourself from the bottom logic .
Method 2: Embedded assembly code
Use variable aliases in dynamically loaded plug-ins , In addition to the dynamic registration method demonstrated above , You can also embed assembly code to : Set a global label to achieve .
Go directly to the sample code :
plugin.c
Source file
#include
asm(".Global alias\_data");
asm("alias\_data = data");
extern int alias_data[];
void func\_stage1(void)
{
printf("libplugin.so: func\_stage1 is called. \n");
*(alias_data + 0) = 100;
*(alias_data + 1) = 200;
}
main.c
Source file
#include
#include
#include
// defined in libplugin.so
typedef void (*pfunc\_init)(int *);
typedef void (*pfunc\_stage1)(void);
int data[100] = { 0 };
void main(void)
{
data[0] = 10;
data[1] = 20;
printf("data[0] = %d \n", data[0]);
printf("data[1] = %d \n", data[1]);
// open libplugin.so
void *handle = dlopen("./libplugin.so", RTLD_NOW);
if (!handle)
{
printf("dlopen failed. \n");
return;
}
// get and call routine function in libplugin.so
pfunc_stage1 func_stage1 = (pfunc_stage1) dlsym(handle, "func\_stage1");
if (!func_stage1)
{
printf("get func\_stage1 failed. \n");
return;
}
func\_stage1();
printf("data[0] = %d \n", data[0]);
printf("data[1] = %d \n", data[1]);
return;
}
Compile instructions :
gcc -m32 -fPIC --shared plugin.c -o libplugin.so
gcc -m32 -rdynamic -o main main.c -ldl
Execution results :
data[0] = 10
data[1] = 20
libplugin.so: func_stage1 is called.
data[0] = 100
data[1] = 200
Let's also take a look at libplugin.so
Symbol information in :
readelf -s libplugin.so | grep data
Summary
This document uses two sample code , It discusses how to use in plug-ins ( Dynamic link library ), Access to real variables through aliases .
I wonder if you have such a question : Use it directly extern
Just declare the externally defined variables , Why bother ?
The truth is right !
however , In some special fields or scenes ( For example, in some secondary development ), Such needs do exist , And it's a strong demand .
If you have any questions , Or there is a task error in the text , Feel free to leave a comment 、 correct .
------ End ------
In the public, 【IOT Internet of things town 】 Background reply keyword :20522, You can get the download address of the sample code .
Now that I see this , If it feels good , Please order one at your convenience 【 Fabulous 】 and 【 Looking at 】 Well !
If you reprint this article , At the end of the text, it must be noted that :“ The official account is from WeChat :IOT Internet of things town ”.
Recommended reading
【1】《Linux Learn from scratch 》 Series articles
【3】 original gdb The underlying debugging principle is so simple
【4】Linux Chinese vs 【 Library function 】 To trace the call of 3 Kind of 【 Pile insertion 】 skill
【5】 Is inline compilation terrible ? After reading this article , End it !
【6】gcc Compile time , Linker arranged 【 Virtual address 】 How is it calculated ?
【7】GCC In the process of linking 【 relocation 】 process analysis
【8】Linux In the process of dynamic linking 【 relocation 】 Underlying principle
Other series : Selected articles 、 Application design 、 The Internet of things 、 C Language .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-rFqdaaIG-1655053816259)(https://img2022.cnblogs.com/blog/1440498/202206/1440498-20220612215545217-1664410615.png)]
Official account of star standard , Read the article for the first time !
边栏推荐
- A. Vacations (DP greed
- Priority analysis of list variables in ansible playbook and how to separate and summarize list variables
- 比较DFS和BFS的优点和缺点及名称词汇
- [RS-422 and RS-485] RS-422 and RS-485 serial interface standard
- [weak transient signal detection] matlab simulation of SVM detection method for weak transient signal under chaotic background
- 对绘制丘岭密度图ridge plot的详细说明、重叠核密度估计曲线overlapping densities、FacetGrid对象、函数sns.kdeplot、函数FacetGrid.map
- AQS - detailed explanation of reentrantlock source code
- C Advanced Programming - features
- Wechat applet - positioning, map display, route planning and navigation
- I always don't understand the high address and high position
猜你喜欢
RT thread simulator lvgl control: button button style
Nfv basic overview
WWDC2022最大的亮点: MetalFX
redis-4. Redis' message subscription, pipeline, transaction, modules, bloom filter, and cache LRU
号称下一代监控系统 来看看它有多牛逼
关于#数据库#的问题:PGADMIN4 编辑sql窗口问题
对绘制丘岭密度图ridge plot的详细说明、重叠核密度估计曲线overlapping densities、FacetGrid对象、函数sns.kdeplot、函数FacetGrid.map
Tidb data migration (DM) Introduction
Xuanwu cloud technology passed the listing hearing: the performance fluctuated significantly, and chenyonghui and other three were the controlling shareholders
Mui mixed development - when updating the download app, the system status bar displays the download progress
随机推荐
I always don't understand the high address and high position
C drawing table and sending mail function
对绘制丘岭密度图ridge plot的详细说明、重叠核密度估计曲线overlapping densities、FacetGrid对象、函数sns.kdeplot、函数FacetGrid.map
[RS-422 and RS-485] RS-422 and RS-485 serial interface standard
Issues related to C # delegation and events
快速排序
Monotone stack top31 of interview must brush algorithm top101
Powerdispatcher reverse generation of Oracle data model
oracle问题,字段里面的数据被逗号隔开,取逗号两边数据
理財產品連續幾天收益都是零是怎麼回事?
Ansible PlayBook的中清单变量优先级分析及清单变量如何分离总结
Login registration
Station B crazy God notes
redis-5. Redis' RDB, fork, copyonwrite, AOF, RDB & AOF are mixed
It's called the next generation monitoring system. Let's see how awesome it is
汇编语言基础:寄存器和寻址方式
ISIS的vsys(虚拟系统)
基于SSM实现水果商城批发平台
MySQL does not recommend setting the column default value to null. Why on earth is this
比较DFS和BFS的优点和缺点及名称词汇