问题描述:

I wanted to write a piece of code in C for my Stellaris launchpad just to turn on the onboard LED by keeping the library usage to minimum. To my surprise, the compiled code was around 800 bytes in size. So to check what was put in to the compiled code by the compiler, I checked the assembly code using a dissambler. It had a lot of code which I didn't write the C code for. I would like to know what those codes are for and how did it enter the compiler setting. I am trying to learn how a compiler behaves and what behind-the-scenes things the compiler is doing. Please help me.

This is my C program:

#include "inc/hw_memmap.h"

#include "inc/hw_types.h"

#include "driverlib/rom.h"

#include "driverlib/sysctl.h"

#define GPIOFBASE 0x40025000

#define GPIOCLK *((volatile unsigned long *)(0x400FE000 + 0x608))

#define FDIR *((volatile unsigned long *)(GPIOFBASE + 0x400))

#define FDEN *((volatile unsigned long *)(GPIOFBASE + 0x51C))

#define FDATA *((volatile unsigned long *)(GPIOFBASE + 0x3FF))

void main(void) {

ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);

GPIOCLK |= (1<<5);

FDIR |= 0xE;

FDEN |= 0xE;

FDATA |= 0xE;

while (1);

}

The only API call I used was to set the Clock setting using a Onchip ROM library. Please check the dissambly code at this pastebin: (The main: is at 0x190.)

http://pastebin.com/wNNsBdtT

网友答案:

The additional code will be CPU initialisation and C runtime initialisation. The source code for this start-up is probably provided with your compiler. In GCC for example it is normally called crt0.s

Depending on your CPU and memory it will probably require some initialisation to set the correct clock frequency, memory timing etc. On top of that the C runtime requires static data initialisation and stack initialisation. If C++ is supported additional code is necessary to call the constructors of any static objects.

Cortex-M devices like Stellaris are designed to run C code with minimum overhead, and it is possible to essentially start C code from reset, however the default start-up state is often not what you want to run your application is since for example this is likley to run at a lower and less accurate clock frequency.


Added 06Dec2012:

Your start-up code is almost certainly provided by the CMSIS. The CMSIS folder will contain CoreSupport and DeviceSupport folders containing start-up code. You can copy this code (or the relevant parts of it) to your project, modify it as necessary and link it in place of the provided code. The CMSIS is frequently updated, so there is an argument for doing that in any case.

Your build log and/or map file are useful for determine which CMSIS components are linked.

相关阅读:
Top