当前位置:网站首页>Embedded UC (UNIX System Advanced Programming) -2
Embedded UC (UNIX System Advanced Programming) -2
2022-07-05 17:04:00 【Orange peel does not stop school】
UC I've been learning for a while , I'm going to tidy up my notes , Send it online , It's convenient to repeat the offer at any time in the future , It is also available for everyone to learn and Exchange , Hope not to collect and eat ashes , Keep learning , Through their own efforts , Add bricks and tiles to the direction you like in this world .
One 、 library
Let's start with the introduction of two concepts :
For starters , Generally, all functions in the program will be implemented in a single source file . This will lead to long compilation time , Not easy to maintain and upgrade , Not easy to develop collaboratively , This is a single model .
Divide different functional modules in the program into different source files . Reduce compilation time , Easy to maintain and upgrade , Easy collaborative development , This belongs to the separation model .
1. Static library
The essence of static libraries is Package multiple target files into one file .
Linking a static library is to put The called code is copied to the calling module in .
Use Programs with static libraries usually Take up more space , Code in the library Once modified , All programs that use this library Must relink .
Programs that use static libraries are The runtime does not need to rely on libraries , Its execution efficiency is high .
The naming form of static library :libxxx.a
Building static libraries :ar -r libxxx.a x.o y.o z.o
Use static libraries : Law 1 :gcc ... -lxxx -L< The library path >
Law two :export LIBRARY_PATH=< The library path >
2. Dynamic library
The biggest difference between a dynamic library and a static library is , Link dynamic libraries and There is no need to copy the code called in the library to the calling module in , Instead, what is embedded in the calling module is just The relative address of the called code in the dynamic library .
If the code in the dynamic library Used by multiple processes at the same time , Only one instance of the dynamic library is needed in the whole memory space , therefore Dynamic libraries are also called shared libraries or shared objects (Shared Object, so).
Modules using dynamic libraries It takes up less space , Even if you modify the code in the library , As long as the interface stays the same , No need to re link .
The code using dynamic library is in Runtime needs to rely on libraries , The efficiency of implementation is slightly low .
Naming form of dynamic library :libxxx.so
Building dynamic database :
gcc -c -fpic xxx.c -> xxx.o
It's usually creating .so When dynamic link library , All have to be added. -fPIC Parameters . -fPIC Works in the compilation phase , Tell the compiler to generate location independent code (Position-Independent Code), In the generated code , No absolute address , All use relative addresses , Therefore, the code can be loaded anywhere in memory by the loader , Can be executed correctly .( Even if you don't add fPIC It can also generate .so file , But there are requirements for source files , For example, because no fPIC Compilation of so Must be loaded into the address space of the user program Redirect All table items , So you can't quote code from other places in it )
Packing command :gcc -shared -o libxxx.so x.o y.o z.o
Using dynamic libraries : Law 1 :gcc ... -lxxx -L< The library path >
Law two :export LIBRARY_PATH=< The library path >
gcc ... -lxxx
Different from the use of static libraries : The dynamic library called by the runtime must be located in LD_LIBRARY_PATH The path represented by the environment variable .
gcc default ( That is, without any explanation ) Link shared library , It can be done by -static Option to force a link to a static library .
3. Dynamic loading dynamic library
#include <dlfcn.h> This header file is not standard c The header file in , It belongs to the system
-ldl : dl Dynamic loading library means , That is, link dynamic load Library , Explain that it is provided by the system Dynamic loading function set for dynamic library
void* dlopen(const char* filename, int flag);
Successfully returned the handle of the dynamic library , Failure to return NULL.
Handle : Equivalent to a clue , Let the system kernel find the corresponding dynamic library , But it does not directly point to dynamic libraries , He just points to a data block , This data block stores information related to the dynamic library , Such a data block is called a handle .(Handle) You only need to get the address of this block to operate .
filename - Dynamic library path , If you only give the file name , According to LD_LIBRARY_PATH Environment variable search dynamic library
flag - Loading mode , Take the following values :
RTLD_LAZY - Delay loading , Only load when using symbols in the dynamic
RTLD_NOW - Immediately load
The dynamic library handle returned by this function It uniquely identifies the dynamic library objects maintained by the system kernel , Will be used as a parameter for subsequent function calls .
void* dlsym(void* handle, const char* symbol);
Function address returned successfully , Failure to return NULL.
handle - Dynamic library handle
symbol - Symbol ( Function or global variable ) name
The function pointer returned by this function is void* type , A cast is required Only the actual function pointer type can be called .
int dlclose(void* handle);
Successfully returns 0, Non zero return from failure .
handle - Dynamic library handle
char* dlerror(void);
If an error occurs before, the error message string will be returned , Otherwise return to NULL.
Two 、 Auxiliary tool
1. Look at the symbol table :nm
List target files (.o)、 Executable file 、 Static library files (.a) Or dynamic library file (.so) Symbols in
Be careful : No, c, Because c It's a local variable , Only when this program runs , Will allocate memory space in the stack , Local variables are not in the executable .
2. Display disassembly information of binary modules :objdump -S xx
3. Delete target file (.o)、 Executable file 、 Static library files (.a) Or dynamic library file (.so) Medium Symbol table and debugging information :strip ( It can be used to hide some information or reduce space )
3、 ... and 、 Error number and error message
1. Express the error through the return value of the function
for example : A function that returns an integer : The error is indicated by returning a value outside the legal value field
int age (char const* name){
...
return 1000;
}
for example : Functions that return pointers : By returning NULL The pointer indicates an error
for example : Functions that do not need to output information by return value : return 0 It means success , return -1 It means failure .
int delete(char const* filename) {
...
return 0;
...
return -1;
}
2. The specific cause of the error is indicated by the error number and error message
#include <errno.h>
Global variables :errno, Integers , Identify the error of the last system call
#include <string.h>
char* strerror(int errnum); // Return error information according to the error number
#include <stdio.h>
void perror(const char* s); // Print error messages for recent errors
printf Functional %m The tag is replaced with the error message of the most recent error
for example :
Although all the error numbers are not 0, But because the error number global variable when the function is executed successfully errno Will not be cleared 0, therefore Out-of-service errno Is it 0 As the judgment condition for the success or failure of the function , Is there an error or It should be determined according to the return value of the function .
Return value = Function call (...);
if ( The return value indicates that the function call failed ) {
according to errno Judge what went wrong
Provide different processing for different errors
}
Four 、 environment variable
Each process has an independent table of environment variables , Each of these entries is a shape such as “ key = value ” Form of environment variables .
grammar : env
The so-called environment variable table is a table with NULL Pointer end character pointer array , Each of these elements is a character pointer , Point to a string that ends with a null character , The string is shaped like ” key = value ” Form of environment variables .
Get the value of the environment variable according to its name
char* getenv(char const* name);
Successfully return the variable value with matching variable name , Failure to return NULL.
name - Environment variable name , The part to the left of the equal sign
Add or modify environment variables
int putenv(char* string);
Successfully returns 0, Failure to return -1.
string - Form like “ key = value ” Form of environment variable string
If its key already exists , Then modify its value , If its key does not exist , Then add a new variable
But it will not affect the environment variables of the parent process .
Add or modify environment variables
int setenv(const char* name, const char* value,
int overwrite);
Successfully returns 0, Failure to return -1.
name - Environment variable name , The part to the left of the equal sign
value - Environment variable value , That is, the part to the right of the equal sign
overwrite - When name The environment variable name represented by the parameter already exists , This parameter takes 0 Keep the original value of the variable unchanged , If this parameter is not 0, Change the value of the variable to value.
Delete environment variables
int unsetenv(const char* name);
Successfully returns 0, Failure to return -1.
name - Environment variable name , The part to the left of the equal sign
Clear environment variables
int clearenv(void);
Successfully returns 0, Failure to return -1.
边栏推荐
- Jarvis OJ 简单网管协议
- 为季前卡牌游戏 MotoGP Ignition Champions 做好准备!
- ECU简介
- composer安装报错:No composer.lock file present.
- sqlserver 做cdc 要对数据库性能有什么要求么
- 齐宣王典故
- Android privacy sandbox developer preview 3: privacy, security and personalized experience
- Facing new challenges and becoming a better self -- attacking technology er
- Excuse me, is the redis syntax used in DMS based on the commands of the redis community version of the cloud database
- 麻烦问下,DMS中使用Redis语法是以云数据库Redis社区版的命令为参考的嘛
猜你喜欢
兰空图床苹果快捷指令
Benji Bananas 会员通行证持有人第二季奖励活动更新一览
Android privacy sandbox developer preview 3: privacy, security and personalized experience
Benji Banas membership pass holders' second quarter reward activities update list
Summary of methods for finding intersection of ordered linked list sets
Precision epidemic prevention has a "sharp weapon" | smart core helps digital sentinels escort the resumption of the city
深潜Kotlin协程(二十一):Flow 生命周期函数
Detailed explanation of use scenarios and functions of polar coordinate sector diagram
How to uninstall MySQL cleanly
如何安装mysql
随机推荐
Explain in detail the functions and underlying implementation logic of the groups sets statement in SQL
Hiengine: comparable to the local cloud native memory database engine
养不起真猫,就用代码吸猫 -Unity 粒子实现画猫咪
tf. sequence_ Mask function explanation case
The survey shows that the failure rate of traditional data security tools in the face of blackmail software attacks is as high as 60%
Jarvis OJ Telnet Protocol
Allusions of King Xuan of Qi Dynasty
Yarn common commands
Clear restore the scene 31 years ago, volcanic engine ultra clear repair beyond classic concert
Jarvis OJ shell traffic analysis
Twig数组合并的写法
调查显示传统数据安全工具面对勒索软件攻击的失败率高达 60%
外盘期货平台如何辨别正规安全?
Is it safe for qiniu business school to open a stock account? Is it reliable?
Jarvis OJ shell流量分析
[729. My schedule I]
WSL2.0安装
飞桨EasyDL实操范例:工业零件划痕自动识别
Deep dive kotlin synergy (XXI): flow life cycle function
干货!半监督预训练对话模型 SPACE