嵌入式C语言进阶:深入理解const关键字的精妙用法

嵌入式C语言开发中static与volatile关键字的实战解析 在嵌入式系统开发中,内存管理和硬件访问是核心基础概念。static关键字通过控制变量的作用域和生命周期,实现了数据封装和模块化设计,提高了代码的安全性和可维护性。volatile关键字则确保编译器不会优化对特殊内存地址(如硬件寄存器)的访问,保证了硬件操作的正确性。这两种关键字在STM32等嵌入式平台开发中尤为重要,广泛应用于中断服务、多任务通信、硬件寄存器操作等场景。通过合理使用static和volatile,开发者可以构建出既高效又可靠的嵌入式系统,特别是在实时性要求高的电机控制、传感器采集等项目中。 阅读详情

请添加图片描述


嵌入式C语言进阶:深入理解const关键字的精妙用法

嵌入式C语言进阶:深入理解static关键字的三种用法
嵌入式C语言进阶:深入理解volatile关键字的精髓
嵌入式C语言进阶:深入理解sizeof操作符的精妙用法
嵌入式C语言进阶:深入理解typedef的强大威力
嵌入式C语言进阶:结构体封装函数的艺术与实践
嵌入式C语言进阶:位操作的艺术与实战
嵌入式C语言进阶:高效数学运算的艺术与实战


前言

在嵌入式C语言开发中,const关键字远不止于定义"常量"那么简单。它是提高代码可靠性、优化内存分配、增强编译器优化的强大工具。本文将深入探讨const在嵌入式开发中的各种精妙用法,帮助您写出更安全、更高效的嵌入式代码。


一、const基础:不仅仅是常量

基本语法与语义

// 最基本的常量定义
const uint32_t MAX_TEMPERATURE = 125;  // 温度上限
const float PI = 3.1415926f;          // 圆周率

// 编译器会阻止对const变量的修改
MAX_TEMPERATURE = 150;  // 编译错误!

嵌入式中的特殊意义

在嵌入式系统中,const的真正价值在于:

  • ​​ROM存储​​:const数据通常被放置在只读存储器中,节省RAM空间

  • ​​编译器优化​​:帮助编译器进行更好的优化

  • ​​代码安全​​:防止意外修改关键参数


二、const与指针:四种组合的深度解析

1. 指向const数据的指针

const uint8_t *p_sensor_data;  // 指针指向的数据不可修改

void process_sensor_data(const uint8_t *data) {
   
   
    // data[0] = 0xFF;  // 错误:不能修改const数据
    uint8_t local_copy = data[0];  // 可以读取
}

​​嵌入式应用​​:传感器数据采集接口,确保原始数据不被修改

2. const指针

uint8_t *const p_buffer = (uint8_t*)0x20000000;  // 指针本身不可修改

void init_hardware() {
   
   
    // p_buffer = (uint8_t*)0x20001000;  // 错误:指针不可修改
    p_buffer[0] = 0xAA;  // 可以修改指向的数据
}

​​嵌入式应用​​:固定硬件寄存器地址映射

3. 指向const数据的const指针

const uint32_t *const p_rom_data = (const uint32_t*)0x08000000;

// p_rom_data = NULL;         // 错误:指针不可修改
// *p_rom_data = 0x12345678;  // 错误:数据不可修改
uint32_t value = *p_rom_data;  // 只能读取
嵌入式基础知识——关键字 本文系统梳理了C语言关键字的分类与特性,涵盖数据类型、存储类别、流程控制、函数相关等核心语法元素。重点解析了C89/C90的32个关键字和C99新增的5个关键字(_Bool、_Complex、inline等),详细介绍了各关键字的作用范围、内存布局、使用限制及常见陷阱。文章特别强调了类型限定符const/volatile的语义差异,inline函数的优化原理,以及restrict指针的性能优势。同时对比了C与C++在关键字处理上的差异,提供了跨平台编程的实用建议和笔试面试中的典型错误示例,帮助开发者深入理解 阅读详情

相关推荐

Vlan的封装模式和端口讲解(Access、Trunk、Hypbrid端口)

Vlan(Virtual Local Area Network)虚拟局域网,将一个物理的LAN在逻辑上划分为多个广播域,在交换机上实现广播域隔离(增强局域网的安全性、限制广播风暴、简化网络管理)Vlan通过将二层数据帧打上Vlan标签(打上Vlan标签也就是封装Vlan),正常情况下,不同Vlan Tag的数据包是无法二层直接互访的,以此来实现广播域的隔离可以理解为一个Vlan对应一个广播域,同一Vlan内的主机可以二层直接通信,不同Vlan间的主机无法二层直接通信。

m0_49864110的博客 5658

数据科学常见模型总结(二)-倾向性得分匹配模型

PSM的核心思想是从未受干预的用户群体中,找到和干预对象一模一样的用户,这样就可以把因果效应归因到干预上。

wudelong0112的专栏 4916

详解如何用爬虫工具批量采集阿里巴巴批发网商品数据

本文主要介绍如何使用后羿采集器的智能模式,免费采集阿里巴巴批发网商品的批发价格、发货时间、是否代发等信息。 采集字段: 商品标题、商品链接、图片链接、标签1、标签2、标签3、价格、30天成交数、 评价、店铺 功能点目录: 如何对采集字段进行配置 如何采集列表+详情页类型网页 采集结果预览: 下面我们来详细介绍一下如何免费采集1688批发网的商品数据,我们以“羽绒服女”为例,具体步骤如下: 步骤一...

weixin_43777427的博客 1万+

Ansys Lumerical 2023 R1.2新功能实战:薄膜铌酸锂调制器仿真全流程解析

本文详细解析了Ansys Lumerical 2023 R1.2在薄膜铌酸锂电光相位调制器仿真中的最新功能与应用。通过实战演示,展示了从电极配置、电场计算到模式分析的全流程,重点介绍了各向异性介电常数支持和多物理场耦合优化等关键技术,助力开发者高效设计高性能光通信器件。

weixin_28454475的博客 1226

小黄鸭机器人技术全解-第 07 章 关节自由度与行程参数

—鸭子歪着头转头时,转的平面是斜的,这正是它"灵动"感的来源。仿真里这是自动的(轴定义在父刚体系),复刻时不需要做任何事——

yolo模型训练找我,AI游戏合作找我 80

核心组件大换血:Backbone与Neck魔改篇:YOLO26结合StarNet结构:2026星状网络在YOLO生态的即插即用实战

本文将介绍如何将StarNet作为Backbone替换YOLO26原生架构,以提升边缘设备上的目标检测性能。文章首先分析了YOLO26在特定场景下的精度瓶颈,指出其通用Backbone设计存在不足。随后深入解析StarNet的核心创新——星操作(Star Operation),这一低维计算却能获得高维特征表达的数学魔术,以及其极简的StarBlock模块设计。通过对比YOLO26原生架构的三大创新与痛点,作者提出两种替换策略:完整替换Backbone或局部替换+Neck联调。文中提供了StarNet核心代码

ZDQ58818的博客 295

第3.1.3章 机器人第三方库实战总结:ROS 2 入门实战及和ROS1的对比,打通机器人开发的任督二脉

本文针对机器人SLAM开发中第三方库的学习痛点,重点介绍ROS 2在SLAM中的应用。文章首先对比ROS 1与ROS 2的核心差异,梳理ROS 2知识图谱,包括节点、话题、服务等核心概念。通过实战项目演示如何构建激光SLAM节点,结合代码详解运行流程。最后给出学习建议,强调动手实践的重要性,帮助开发者快速掌握ROS 2在SLAM开发中的关键应用。

行知SLAM 186

使用MCAL的Fee模块集成ETAS存储协议栈

由于ETAS Fee模块导致初始化时间较长,且集成占用的内存较大,所以最终考虑使用MCAL中的Fee模块来集成ETAS的Nvm模块,本文介绍具体的集成方法注意:本文所涉及的集成前提是原有的ETAS协议栈已正常使用使用IFX Fee需要手动配置Fee,可能有出错的风险,最好是利用脚本自动生成代码来实现。另外,需要注意IFX的Fee中block数据没有CRC校验,如果使用该Fee,建议Nvm中加CRC校验(ETAS Fee中block自带CRC,可以不需要Nvm Crc),防止数据被意外篡改导致的异常。

赞的博客 415

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 嵌入式C语言进阶:深入理解static关键字的三种用法
下一篇: 嵌入式C语言进阶:深入理解volatile关键字的精髓
智驾
博客等级 码龄11年 6680粉丝 574原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智驾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址