【无标题】

C语言中静态变量存在的段

概要

在kendryte k210上实验探究未初始化的全局变量,未初始化的静态全局变量,初始化的全局变量,初始化的静态全局变量,未初始化的静态局部变量,初始化的静态局部变量所存在的段。

先说结论

直接看表格

全局变量全局静态变量局部静态变量
初始化.data.data.data
未初始化.bss.bss.bss

代码

/* Copyright 2018 Canaan Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <bsp.h>
#include <sysctl.h>

#include "sleep.h"

#define name(x) #x

/* 定义在链接脚本中的bbs段首与段尾 */
extern unsigned int _bss;
extern unsigned int _ebss;

/* 定义在链接脚本中的data段首与段尾 */
extern unsigned int _data;
extern unsigned int _edata;

/* 测试的全局变量 */
int x;
int y = 1;
int z;
/* 测试的静态全局变量 */
static int b;
static int c = 1;

/* 段检测函数 */
void printSection(void *a, char str[100]) {
  if (a > (void *)&_bss && a < (void *)&_ebss) {
    printf("%s locate in bss\n", str);
  } else if (a > (void *)&_data && a < (void *)&_edata) {
    printf("%s locate in data\n", str);
  } else {
    printf("%s locate in other section\n", str);
  }
}

/* 静态变量测试 */
void static_test() {
  static int d;
  static int e = 1;
  printf("static variable test\n");
  printSection(&b, name(b));
  printSection(&c, name(c));
  printSection(&d, name(d));
  printSection(&e, name(e));
}

int main(void) {
  z = 2;
  printf("normal variable test\n");
  printSection(&x, name(x));
  printSection(&y, name(y));
  printSection(&z, name(z));
  static_test();
  while (1) {
    msleep(3000);
  }
  return 0;
}

执行结果

normal variable test
x locate in bss
y locate in data
z locate in bss
static variable test
b locate in bss
c locate in data
d locate in bss
e locate in data
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值