GNU Freestanding (Naked) C ARM cross-development environment creation and testing

Publisher:见贤思奇异果Latest update time:2021-10-31 Source: eefocusKeywords:GNU Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

0 Origin

In my blog post, Building and Testing the GNU ARM Cross-Assembly Environment, I explained in detail how to create and use the GNU ARM assembly environment. In actual development, there are very few codes written directly in assembly language. Assembly code is only used when the system is started and when performance requirements are extremely demanding. In terms of readability, portability, and logical expression, C language is much better than assembly language. It is this advantage of C language that created the Unix world and the lively scene of Linux being compiled and run smoothly on multiple platforms.


Therefore, in the field of embedded development, C language is the main language. Before using the development program to run on ARM, you must build a useful C cross-compilation environment. In the blog post Freestanding C and the analysis of the generation principle of the cross compiler, the concept of Freestanding C and the principle of cross-compiler construction are explained. Building a complete Hosted C cross compiler is a rather complicated process, especially for GCC, the process is full of difficulties and obstacles. In order to avoid frustration for beginners, we start with the simple, first build a Freestanding C cross compiler, and then write a specific C project to test it.


1 Construction of Freestanding C

The GCC project has two main functions. One is to provide front-end compilers for multiple languages ​​such as C, C++, Fortran, etc., which is responsible for translating high-level language codes into assembly codes. The other is to be the main entrance to the entire development environment, responsible for calling other assembly and linking tools to control the entire compilation-->assembly-->linking process. It can be seen that GCC itself cannot work independently and must rely on externally provided assembly, linking and other tools. The most famous software that provides these external tools is binutils.


Although in theory there is no need to install gcc and binutils in order, in fact, during the gcc compilation process, it is necessary to run the tools provided by binutils to perform tests and dynamically control its own source code compilation based on the test results. Therefore, binutils must be installed first before gcc can be compiled and installed.


1.1 Using binutils to build a cross-assembly environment

For details on the compilation and installation of binutils, please refer to the Building and Testing of GNU ARM Cross-Assembly Environment. This article will not repeat the details. For ease of reference, only the configuration command of binutils is given:


../binutils-2.27/configure --prefix=/home/smstong/ARM --target=arm-linux-gnueabihf


When you configure GCC later, you need to provide configuration parameters that are exactly the same.


1.2 Using GCC to build a Freestanding C cross-compilation environment

1.2.1 Download the latest GCC source code package from the official website

The official website of GCC is http://www.gnu.org/software/gcc, which is the base camp of GCC and the core component of the entire GNU.


Then, enter the gcc-6.2.0 folder and execute the ./contrib/download_prerequisites script, which will automatically download the libraries isl, mpc, gmp, mpfr, etc. required to compile GCC. I don't know why these packages are not directly included in the GCC source code package for download, and users have to download it again.


Other common compilation environments: local GCC, GNU make, perl, awk, bash, etc., will not be discussed here. These basic development environments have been installed on general Linux hosts used for development.


1.2.2 Configuration and Installation

The GCC project also uses GNU autotools to manage the compilation process, so the first step to generate it must be to execute the configure command. Like binutils, gcc also recommends separating the build directory from the source directory, so create a new directory called build-gcc and then enter this directory to perform the entire build process.


mkdir build-gcc

cd build-gcc

../gcc-6.2.0/configure --prefix=/home/smstong/ARM # Same as binutils configuration

                         --target=arm-linux-gnueabihf # Same as binutils configuration

                         --enable-languages=c # Generate only the C compiler

                         --without-headers # Do not use header files

                         --disable-multilib # Do not generate multiple library versions

make all-gcc # Note that the target here is all-gcc, which is freestanding C

make install-gcc # The corresponding installation is only GCC


After the installation is complete, you will find the newly generated cross compiler /home/smstong/ARM/bin/arm-linux-gnueabihf-gcc, and a hard link at /home/smstong/ARM/arm-linux-gnueabihf/bin/gcc. Execute the following command to test:


[smstong@centos192 bin]$ ./arm-linux-gnueabihf-gcc -v

Use built-in specs.

COLLECT_GCC=./arm-linux-gnueabihf-gcc

COLLECT_LTO_WRAPPER=/home/smstong/ARM/libexec/gcc/arm-linux-gnueabihf/6.2.0/lto-wrapper

Target: arm-linux-gnueabihf

配置为:../gcc-6.2.0/configure --prefix=/home/smstong/ARM/ --target=arm-linux-gnueabihf --enable-languages=c --without-headers --disable-multilib

Thread model: POSIX

gcc version 6.2.0 (GCC)


2 Test Environment

Target machine environment:

(1) Hardware platform: TQ2440 development board, Soc CPU is Samsung 2440, ARM920T core.

(2) Norflash is equipped with u-boot, which can download the program to the specified physical memory address and execute it through tfgtp

(3) Nandflash is installed with Linux 2.6 system and tftp client tool.

Development host:

(1) CentOS 7 PC machine

(2) TFTP server is installed and the service directory is /var/www/tftpboot/.


3 C program test example in bare metal environment

2.1 Project source code

Source code file structure:


.

├── Makefile

├── test.c

├── test.lds

└── test.s


test.c


#define rGPBCON (*(volatile unsigned*)0x56000010)

#define rGPBDAT (*(volatile unsigned*)0x56000014)

#define rGPBUP  (*(volatile unsigned*)0x56000018)


void init()

{

    /* Initialize led1 */

    rGPBCON &= ~(3<<10);

    rGPBCON |= (1<<10);

    rGPBUP &= ~(1<<5);


    /* Turn off led1 */

    rGPBDAT |= (1<<5);

    return;

}


test.lds


ENTRY(init)

SECTIONS {

    . = 0x30000000;

    .text : {

        *(.text)

        *(.rodata)

    }

    .data ALIGN(4): {

        *(.data)

    }

    .bss ALIGN(4): {

        *(.bss)

    }

}


Makefile


CC = arm-linux-gnueabihf-gcc

LD = arm-linux-gnueabihf-ld

OBJCPY = arm-linux-gnueabihf-objcopy


all: test.bin

    sudo cp test.bin /var/lib/tftpboot/

test.bin: test

    $(OBJCPY) -O binary $< $@


test: test.o

    $(LD) --script=test.lds -o $@ $<


test.o: test.c

    $(CC) -c $<

.PHONY: clean

clean:

    rm -rf *.o test test.bin


2.2 Compilation and linking instructions

The default entry point name of the cross-linker is _start, the default code segment base address is 0x00001074, and the generated executable file format is elf. If we want the program to run on a bare metal machine, we need the code segment base address to be 0x30000000, and the file format to be a pure binary image. This can be easily done with the link script. In addition, we also manually specify the program entry point as the init function.


Use u-boot in Norflash to load the generated test.bin to physical memory 0x30000000 and execute it. You will find that LED1 is turned off. And after the execution is completed, it automatically returns to u-boot. This is because the last statement of the init() function is a return statement.


2.3 Look at the assembly code generated by the compiler

When using gcc test.c -c, gcc will hide the intermediate assembly code file. In order to see this intermediate file, you need to call gcc through the -S option to generate the assembly code file.


arm-linux-gnueabihf-gcc -S test.c

1

The above command will generate the test.s file as follows:


    .eabi_attribute 18, 4

    .file   "test.c"

    .text

    .align  2

    .global init

    .syntax unified

    .arm

    .fpu softvfp

    .type   init, %function

heat:

    @ args = 0, pretend = 0, frame = 0

    @ frame_needed = 1, uses_anonymous_args = 0

    @ link register save eliminated.

    str fp, [sp, #-4]!

    add fp, sp, #0

    ldr r2, .L2

    ldr r3, .L2

    ldr r3, [r3]

    bic r3, r3, #3072

    str r3, [r2]

    ldr r2, .L2

    ldr r3, .L2

    ldr r3, [r3]

    orr r3, r3, #1024

    str r3, [r2]

    ldr r2, .L2+4

    ldr r3, .L2+4

    ldr r3, [r3]

    bic r3, r3, #32

    str r3, [r2]

    ldr r2, .L2+8

    ldr r3, .L2+8

    ldr r3, [r3]

    orr r3, r3, #32

    str r3, [r2]

    nop

    sub sp, fp, #0

    @ sp needed

    ldr fp, [sp], #4

    bx  lr

.L3:

    .align  2

.L2:

    .word   1442840592

    .word   1442840600

    .word   1442840596

    .size   init, .-init

    .ident  "GCC: (GNU) 6.2.0"

    .section    .note.GNU-stack,"",%progbits


Through the assembly code generated by gcc, we can also learn the basic syntax of GNU ARM assembly.


4 Freestanding C program test examples under Linux environment

Because it is a Freestanding C environment, there is still no standard C library available even in Linux. And C language cannot directly execute soft interrupt instructions to call Linux system calls, which makes the API provided by the operating system completely unusable! (Assembly language can directly call the system API through swi instructions) It can be seen that under the operating system, if there is no C library, C language cannot operate the hardware at all, and it is impossible to control the LED lights on the development board, and even cannot print a simple hello world. How sad it is!


In order to facilitate testing, we have to use the help of assembly language and adopt a mixed programming method of C language and assembly language. The assembly language provides a function to print a string and a function to exit the process, which are called by the C language.

In fact, this is equivalent to implementing a super-simplified POSIX system call C library in assembly language.

When C language and assembly language call each other, they must comply with the corresponding function calling specifications and APCS (ARM Process Call Standard). Please learn them by yourself.

[1] [2]
Keywords:GNU Reference address:GNU Freestanding (Naked) C ARM cross-development environment creation and testing

Previous article:ARM-GCC has compilation errors for function pointer calls? [The cause has been found]
Next article:Construction and testing of GNU ARM cross-assembly environment

Recommended ReadingLatest update time:2024-11-15 07:15

ARM programming mode and seven working modes
1. Programming mode: The basic settings of the ARM CPU and the rules to be followed when programming, such as the size of instructions used by the CPU. 1. ARM basic settings use 32-bit architecture 2. ARM's agreement: Byte 8bits will never change Halford: 16 bits (2 bytes) half word Word: 32 bits 3. Most ARM cores pro
[Microcontroller]
Qemu builds ARM vexpress development environment (I)
Embedded development is inseparable from hardware devices such as development boards and peripherals. However, if you just want to study the Linux kernel, the architecture and working mode of the Linux kernel, you need to modify some codes, recompile and burn them into the development board for verification, which may
[Microcontroller]
C51 LCD (LMC1602A) Experiment 2
Because I couldn't find this LCD screen on protues, I didn't take a screenshot. It has been verified to be correct. Program 1: Display a 1 on the LCD screen //Display a character on the LCD screen #include reg52.h #define uchar unsigned char #define uint unsigned int //Port settings sbit lcden=P3^4; sbit lcdr
[Microcontroller]
Azure ARM (7) ARM Template - Edit using Visual Studio
  The ARM Template introduced previously all uses a text editor to edit JSON files.   This article will introduce how to use Visual Studio to edit JSON Template.   This article was compiled using Visual Studio 2015 with Update 3, with Azure SDK 2.9 installed.   If you are using Visual Studio 2013 and Azure SDK 2
[Microcontroller]
Azure ARM (7) ARM Template - Edit using Visual Studio
Differences between ARM and X86 CPU architectures
CISC (Complex Instruction Set Computer) and RISC (Reduced Instruction Set Computer) are two architectures of current CPUs. The difference between them lies in different CPU design concepts and methods. Early CPUs were all CISC architectures, and its design purpose was to use the least machine language instructions to
[Microcontroller]
Differences between ARM and X86 CPU architectures
Linux driver: s3c2410_ts/s3c2440_ts module loading process
Preface By analyzing the s3c2410_ts/s3c2440_ts module loading process, the bus-device-driver model and input subsystem framework in the Linux driver are analyzed . Main process analysis diagram s3c2440_ts main process analysis system initialization MACHINE_START(SMDK2410,"SMDK2410") MACHINE_START(SMDK2410, "SMDK241
[Microcontroller]
ARM Assembly Programming Basics VI - Other Addressing Modes and Other Instructions
Now we have all the knowledge to write simple ARM assembly programs, but if we want to write more complex ARM programs, we must master more addressing modes and instructions, which is the focus of this article. We have learned the three most commonly used addressing modes in the article "Basic Addressing Modes and Bas
[Microcontroller]
Install arm-linux-gnueabi-xxx compiler in Ubuntu
Installing the ARM-Linux-GCC toolchain Assuming your Ubuntu system is up to date, you only need to execute the following command to successfully install it: sudo apt-get install gcc-arm-linux-gnueabi After the installation is complete, type directly in the terminal arm-linux-guneabi-gcc -v
[Microcontroller]
Install arm-linux-gnueabi-xxx compiler in Ubuntu

Recommended posts

[MIL-TI AM62x Development Board - Trial Evaluation] 1. Late Unboxing
#【MIL-TIAM62xDevelopmentBoard-TrialEvaluation】1.LateunboxingRecently,theschoolisattheendofthesemester,andIamreallybusy.Iamverysorrythattheunboxingreportislate.WhenIlearnedfromthestaffthatIpassedtheapplicat
paope TI Technology Forum
Circuit Design of Robot Positioning System Based on MSP430
Formobilerobotsworkinginoutdoorenvironments,inertialnavigation/satellitecombinednavigationisusuallyused.Theinertialnavigationsystemhastheadvantagesofcompleteautonomy,stronganti-interference,goodconcealmentabilityandco
火辣西米秀 Microcontroller MCU
USB power supply and DC power supply issues
The12Vswitchingpowersupplyisinput,andthecircuitboardhas12Vto5Vand5Vto3.3V.Nowweneedtoaddafunctiontothecircuitboard,USBtoserialport,asshowninthecircuitdiagram.TheVBUSoftheUSBinterfaceisalso5V.Whatshou
平漂流 PCB Design
【Digi-Key Follow me Issue 2】Task Submission
Part1:VideoIntroduction Videoaddress:https://training.eeworld.com.cn/course/68150 Part2:TaskSubmission Task1]ControlthescreentodisplayChinese: Theimplementationcodeisasfollows: importboard importdisplayio from
未见 DigiKey Technology Zone
Deadbeat Control Inverter Based on DSP
 Ascomputersandvariousprecisionautomationequipmentandelectronicequipmentarewidelyusedincommunications,industrialautomationcontrol,officeautomationandotherfields,inverters,asanimportantpartofUPS|0"UPS,havebeenrapidly
Jacktang DSP and ARM Processors
About the problem of generating plate making files
Iwouldliketoaskifyoucan'ttellfromtheGerberfilewhetherthePCBwasmadebyALTINUM,MentorGraphicsPADS,CadenceOrCAD,orP-CAD? ThecommentsintheGERBERfilewillcontaininformationaboutthesourcefile;butifthesecomments
深圳小花 PCB Design
Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号