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
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 <stdio.h>
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 <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
// 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 <stdio.h>
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 <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
// 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 .
Official account of star standard , Read the article for the first time !
C Language : How to give an alias to a global variable ? More articles about
- 《C Introduction to language 1.2.3— An old bird's C Language learning experience 》— Another bad book and Fake Book concocted by Tsinghua University Press
<C Introduction to language 1.2.3— An old bird's C Language learning experience >— Another bad book and Fake Book concocted by Tsinghua University Press [ Xue Feiping ] Just so 15 page , Yes 80 Multiple errors . The most serious ones are : It's all about C++ Code , Not at all C The language code . ...
- C Introduction to language :02. first C Language program
One . Selection of development tools (1) Tools that can be used to write code : Notepad .UltraEdit.Vim.Xcode etc. (2) choice Xcode Why : Apple's official development tool . Simplify the development process . It has highlight function (3) Use Xcode newly build ...
- Write a C Language functions , Ask for a url, Output this url It's the home page 、 A table of contents page or something url
Write a C Language functions , Ask for a url, Output this url It's the home page . A table of contents page or something url home page . A table of contents page or something url The following form is called the home page : militia.info/ www.apcnc.com.cn/ htt ...
- C Language defines global variables
(1) stay C Problems with defining variables in the header file of the language It's better not to define something in the header file . For example, global variables : /*xx The header file */ #ifndef _XX_ The header file .H #define _XX_ The header file .H in ...
- C Summary of language local variables and global variables
1. Can a local variable have the same name as a global variable ? answer : can , The part will shield the whole . To use global variables , Need to use "::" Local variables can have the same name as global variables , When you refer to this variable within a function , You use local variables with the same name , Instead of using global variables ...
- Scheme Introduction to language examples -- How to write a “ New Coronavirus infection risk testing program ”
A programming language that pupils can use 2020 Primary and secondary schools are affected by the epidemic in spring , School hasn't started yet , The child stayed at home and said he wanted to do a research project required by the school , I'll tell you to do a small project on how to learn mathematics through programming , Using the simplest computer language to solve primary school mathematics problems ...
- C The difference between language local variables and global variables .——Arvin
Local variables use the same memory block to store a value in the entire class . Global variables exist for the following reasons : 1, Using global variables takes up more memory ( Because of its long life ), But in today's high computer configuration , This is not a problem , Unless you use a giant ...
- C Language : An example of linked list implementation
problem : Write a program to input all the movies you see in a year and all kinds of information about each movie ( Simplification problem : Only the title and evaluation are required for each movie ) Linked list implementation : #include<stdio.h> #include<stdli ...
- C Language stay VS A very interesting error report in the environment :stack around the variable was corrupted
Make a very simple one today oj Let's review c Language The title is as follows Input 3 Positive integer Output The inverse positive integer The code is as follows : #include"stdio.h"int main(){ float h,su ...
- About c Language char One of the types of input and output bug
subject Enter an integer n, Next n Enter two characters separated by a space on each line . For each pair of characters , Compare the size relation and output the result of comparison :1.0.-1. The solution code is as follows : #include<stdio.h> i ...
Random recommendation
- Set up Android studio The theme of the content
Download theme Jar package http://color-themes.com/?view=theme&id=563a1a6e80b4acf11273ae76 Import the theme : File->Import s ...
- python learning ” Iterations from entry to mastery “
In the process of development , If I give you one list perhaps tuple, We can go through for Loop through this list perhaps tuple, This traversal we call iteration (Iteration). stay Python in , Iteration is through for ... in ...
- android gridview Layout , Press and hold a , All items show the deleted icon
I have been busy with project development recently , I haven't written a blog for a while , What I want to share with you today is long press gridview One of the items in shows the Delete Icon , Click an item to delete , Press and hold the cancel delete icon . gridview The layout file is as follows : <?xm ...
- With the help of XShell, Use linux command sz It is very convenient to download the files on the server to the local , Use rz The command is to upload the local file to the server .
rz Yes, it will window The document was transmitted to linux Server , To carry out rz Directory of commands sz Can be linux File sent to windows On , You can choose a directory . https://www.google.com/ncr Log in the ...
- java_25 FileReader Classes and FileWriter class
1.FileWriter 1.1FileWriter For writing character streams . To write to the original byte stream , Please consider using FileOutputStream. public class Demo { public stati ...
- jsfl Common custom methods
// Create folder function creatFile(fileURl) { if (FLfile.createFolder(fileURl)) { //alert(" Create success "+ ...
- spring boot Transaction support
- Find and output 11~999 The palindrome number between m
Find and output 11~999 Number between m, It meets the m.m2 and m3 All are palindromic numbers . Palindrome : All numbers are left-right symmetric integers . for example :11 Meet the above conditions 112=121,113=1331 The method of judging whether a number is palindrome number : Find the reverse order of the number ...
- regex & form validation & phone
regex & form validation https://regexper.com/ https://gitlab.com/javallone/regexper-static https ...
- Bootstrap Of js Introduction to paging plug-in properties
Bootstrap Paginator It's based on Bootstrap Of js Paging plug-ins , It's very functional , I think this plug-in is impeccable . It provides a series of parameters to support the user's setting system , Provides a common way to get plug-ins at any time ...