概要
在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