当前位置:网站首页>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 maindlopen 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 !
边栏推荐
- P6154 游走(记忆化搜索
- Compilation and development process of Quanzhi v3s environment
- socket编程2:IO复用(select && poll && epoll)
- SDN basic overview
- A solution to the problem that there is always a newline character when C merges multiple RichTextBox contents
- Wechat applet - positioning, map display, route planning and navigation
- 关于c#委托、事件相关问题
- Table access among Oracle database users
- MySQL query timeout control
- 6. system call
猜你喜欢

TCP协议的三次握手过程和四次挥手过程以及为什么要这样? ------一二熊猫

WWDC2022最大的亮点: MetalFX

Tree list under winfrom treelist related

Powerdispatcher reverse generation of Oracle data model

redis-7. Redis master-slave replication, cap, Paxos, cluster sharding cluster 02

RT thread simulator lvgl control: button button style
![[weak transient signal detection] matlab simulation of SVM detection method for weak transient signal under chaotic background](/img/11/d6cd333a2fa56af2dc61b7597f1ada.png)
[weak transient signal detection] matlab simulation of SVM detection method for weak transient signal under chaotic background

RT thread simulator lvgl control: button button event

论文笔记: 多标签学习 BP-MLL
![[RS-422 and RS-485] RS-422 and RS-485 serial interface standard](/img/08/e50df07d387b2f2d57a518caedc795.jpg)
[RS-422 and RS-485] RS-422 and RS-485 serial interface standard
随机推荐
通过函数seaborn.cubehelix_palette生成顺序调色板
Socket programming 2:io reuse (select & poll & epoll)
About database: pgadmin4 editing SQL window
FTP_ Manipulate remote files
Implementation of fruit mall wholesale platform based on SSM
Xuanwu cloud technology passed the listing hearing: the performance fluctuated significantly, and chenyonghui and other three were the controlling shareholders
The biggest highlight of wwdc2022: metalfx
Quick sort
RT thread simulator lvgl control: button button style
AQS - detailed explanation of reentrantlock source code
TXT_ File encryption and compression
NFV基本概述
关于oracle的函数。
Personal JS learning notes
RT-Thread 模拟器 simulator LVGL控件:button 按钮事件
Oracle problem: the data in the field is separated by commas. Take the data on both sides of the comma
Ticdc introduction
MySQL row column conversion (updated version)
The management practice of leading enterprises has proved that what is the core of sustainable development of enterprises?
How is it that the income of financial products is zero for several consecutive days?