really strange error on my side. I am programming a firmware for a Cortex-M4f running Nucleus RTOS. For my application I have some prebuilt static libraries (e.g. libexternal.a) which expect an global struct which must be provided by the application (declared extern inside the static library).
From within my application code I can access the struct just fine, but from within the code of the static library I always get an HardFault interrupt.
Through debugging I found that the processor tries to access the struct on the wrong address. Here is some example pseudo-code:
appconfig.c
struct AppConfiguration g_appconfig = {
/* initialize everything statically */
};
main.c
include <staticlib.h>
void main(){
g_appconfig.somemember = 1 /* this works */
staticlib_lib_init();
}
Everything below is part of the static library and prebuilt befor compiling the application.
appconfig.h
struct AppConfiguration{
uint32_t somemember;
};
staticlib.h
#include "appconfig.h"
extern struct AppConfiguration g_appconfig;
void static_lib_init();
staticlib.c
#include "staticlib.h"
void static_lib_init(){
g_appconfig.somemember = 1 /* causes a HardFault */
}
The static library is compiled with flags:
-ffunction-sections
-fdata-sections
-fno-builtin-memcpy
-DARM_MATH_CM4=1
-mthumb
-mcpu=cortex-m4
-mfloat-abi=soft
-fPIC
-Wno-unused-but-set-variable
and the application with flags:
-ffunction-sections
-fdata-sections
-fno-builtin-memcpy
-mthumb
-mcpu=cortex-m4
-g
-mfloat-abi=soft
Through debugging I discovered that the static library tries to access g_appconfig at the wrong Memory address. E.g.
g_appconfig starts at address 0x2000061c and static_lib_init() tries to access it at address 0xff7f4342. My SRAM is 320k large starting at 0x2000000 and my ROM is 2MB large starting at 0x8000000. So it makes no sense to access memory at 0xff...... (propably some hardware register or anything else).
Dissassembly of static_lib_init() looks like following:
00000000 <static_lib_init>:
0: b5f0 push {r4, r5, r6, r7, lr}
2: b08f sub sp, #60 ; 0x3c
4: af06 add r7, sp, #24
6: 6178 str r0, [r7, #20]
8: 6139 str r1, [r7, #16]
a: 60fa str r2, [r7, #12]
c: 60bb str r3, [r7, #8]
e: 4cf9 ldr r4, [pc, #996] ; (3f4 <static_lib_init+0x3f4>)
10: 447c add r4, pc
12: 4bf9 ldr r3, [pc, #996] ; (3f8 <static_lib_init+0x3f8>)
14: 58e3 ldr r3, [r4, r3]
16: 461a mov r2, r3
18: 2301 movs r3, #1
1a: f8c2 30d0 str.w r3, [r2, #208] ; 0xd0
r2
should contain the starting address of g_appconfig
(#208 is the offset of the element I want to access in my realworld code), but while debugging contains 0xff7f4342.
Any idea how this could happen? Shouldn't the linker replace the address of g_appconfig in the resulting static library while linking?