embedded gnu/linux session 2 gcc and make - bfh · embedded gnu/linux session 2 gcc and make ......
TRANSCRIPT
Embedded GNU/Linux
Session 2
GCC and MakeMartin Aebersold BFH-TI Dipl. El.-Ing. FH
Dr. Franz Meyer BFH-TI Prof. em.
GNU / Linux
Electrical and Communication Technology GCC & Make-2
GNU/Linux
GNU Compiler Collection (GCC)
Overview and Tips on the GCC Compiler Toolchain and
Binutils
GNU / Linux
Electrical and Communication Technology GCC & Make-3
GNU/Linux
GCC Background
● Original author – Richard M. Stallman 1983● A critical piece of a free operating system● Part of the GNU Project● The name “GNU” is a recursive acronym for “GNU's Not Unix!”; ● Managed by Free Software Foundation (FSF)● Licensed under GNU General Public License (GNU GPL)● Initially named “GNU C Compiler”
Richard Stallman
GNU / Linux
Electrical and Communication Technology GCC & Make-4
GNU/Linux
Development History
● GCC Development Dates: 1984 Started GCC 1987 First release (1.0); 1991: Linus ported GCC (1.40) 1992 Release 2.0 included C++ support 1997 Started experimental branch (EGCS) 2001 Release 3.0 in 2001 incorporated EGCS 2009 Release 4.3.3, January 2009 2013 Release GCC 4.8.2, October 16 2013 2015 Current release is GCC 5.3, December 4 2015
GNU / Linux
Electrical and Communication Technology GCC & Make-5
GNU/Linux
GNU Philosophy● Free software, not necessarily free of cost
● But liberty to use, modify, and redistribute with limited restrictionsdesigned to perpetuate freedom (no proprietary modifications)
● Distributors can sell installations, and support, but must providethe source code and not restrict further copying and redistribution
● Free Software Foundation operates on sales of books and donations of money, time, and equipment
● Provide a free operating system
● To support a proprietary-software free environment to work andcommunicate
GNU / Linux
Electrical and Communication Technology GCC & Make-6
GNU/Linux
Supported Platforms (1/2)● GCC supports worlds widest selection of processors and platforms● Supports most platforms available today● Processor & system manufactures port GCC to their hardware first
● 32-bit CPU ARM AVR32 IA-32 (x86) Power-PC R8C / M16C / M32C Sun Sparc Motorola M68k DEC Alpha, VAX MIPS S/390
● 64-bit CPU AMD64 IA-64 (Intel Itanium) PowerPC Sun UltraSparc IBM POWER / POWER4 DEC Alpha MIPS S/390x IBM Cell
● DSP ADI Blackfin DSP16xx TI TMS320C3x TMS320C4x C6x
● Multimedia D30V
GNU / Linux
Electrical and Communication Technology GCC & Make-7
GNU/Linux
Supported Platforms (2/2)● Microcontroller
PowerPC ARM AVR Motorola 68HC11 / 68HC12 Renesas H8/300 ATMEL AVR TI MSP430
● Other Embedded Processors CRX Vitesse IQ2000 Renesas M32C / M32R Xtensa Zilog Z80 Microblaze and NIOS (FPGA)
● OS / System Linux MS-Windows / MSDOS SVR4 (UNIX) HPUX FreeBSD / NetBSD Solaris VAX Ultrix AIX IRIX Mac OS X VxWorks Cray Unicos/Mk
GNU / Linux
Electrical and Communication Technology GCC & Make-8
GNU/Linux
Supported Languages● List of languages supported by GCC
C (gcc command) C++ (g++ command) Objective-C / Objective-C++ (gcc command) Fortran (g77 command) Java (gcj command) Ada (gnat command) Assembly language of every supported processor (as
command)
Other languages are supported with “front-end” interfaces that are not built-into GCC.User must obtain these front-ends from other sources
Pascal, Mercury and COBOL
GNU / Linux
Electrical and Communication Technology GCC & Make-9
GNU/Linux
GCC Naming Convention
To avoid confusion, the embedded Linux community adopteda target prefix in naming a binutil that is intended for the target.
The prefix are the following:
1. i386-linux for x86 target 2. arm-linux-gnueabihf for ARM target with floating point
arithmetic in hardware 3. ppc-linux or powerpc-linux for PPC target 4. mips-linux for MIPS target
Thus, ar will be named as arm-linux-ar if we build binutils for ARM target board.
GNU / Linux
Electrical and Communication Technology GCC & Make-10
GNU/Linux
GNU Binutils (1/2)
as Assembler popularly known as GAS (Gnu ASsembler)
ar A utility for creating, modifying and extracting
from archives
gprof GNU profiling; collects run-time function timing
gcov GNU coverage; collects line by line execution counts
ld Linker
nm Name; list symbols in object files
GNU / Linux
Electrical and Communication Technology GCC & Make-11
GNU/Linux
GNU Binutils (2/2)
objcopy Copy's and translates object files.
objdump Object dump; disassemble
ranlib Generates an index to the contents of an archive
strip Removes the symbol table from an object file
strings Lists printable strings from files
GNU / Linux
Electrical and Communication Technology GCC & Make-12
GNU/Linux
Compiler Toolchain• Commands
gcc C compiler front-end
g++ C++ compiler front-end
cpp Preprocessing (1st step)
gcc / g++ Compilation (2nd step)
as Assembly (3rd step)
ld Linking (4th step)
• Front-end command is typically used to perform all compile steps, thereby hiding the individual steps
GNU / Linux
Electrical and Communication Technology GCC & Make-15
GNU/Linux
Summary of the Major Features (1)
● Large number of supported platforms● Optimizing compiler● Substantial optional warning messages● Native compiler● Cross-compiler (target different than the one running GCC)● Written in C with modular design
Allows new languages to be used on any supported processor Allows new processors to use any supported language
● Compiles itself● Several currently supported languages
GNU / Linux
Electrical and Communication Technology GCC & Make-16
GNU/Linux
Summary of the Major Features (2)
● Well documented
● Command line interface Allows for Integrated Development Environments (IDE) like Eclipse Easy to port
● Supports dynamic libraries for faster execution and smaller executable
● Free software (most important) Allows anyone to add a language, a processor, a feature, or fix a bug Allows enhancements to be shared Large development community increases number of features and
provides support
GNU / Linux
Electrical and Communication Technology GCC & Make-17
GNU/Linux
Error / Warning Messages● Preprocessing
#if statement syntax Comment syntax (nested C-style) Macro syntax Missing include files Recursion for include files is too deep
● Compilation (not exhaustive list) Statement syntax Uninitialized or undeclared variable
(undeclared function) Unused variable / parameter Type mismatch or conversion problem Missing prototype Standards compliance Unknown #pragma type
● Assembly None (if the assembly file created by GCC)
● Linking Missing object file or static library file Missing “extern” symbol Wrong or corrupted file format of an input file main() function not defined
● Running Dynamic library not found or could not be
loaded Memory access privilege violation Arithmetic exception (divide by zero) Illegal instruction
GNU / Linux
Electrical and Communication Technology GCC & Make-18
GNU/Linux
Compiler Front-end (gcc / g++ commands)
● Wrapper that coordinates compile sequence
● Provides single (language dependent) command to interface to all the compile steps
● Reduces complexity to one command
● Chooses correct compile steps based on input file extension
● Layered user interface approach allows simple usage as well as more powerful complex usage
● Example below compiles source file into an executable and warns of any major issues:
$ gcc -Wall hello.c -o hello
GNU / Linux
Electrical and Communication Technology GCC & Make-19
GNU/Linux
Command Line Options
• Recommended options for warning: ansi -pedantic -Wall -W –WconversionWshadow -Wcast-qual -Wwrite-strings
Note that using the -ansi option with C source code will cause an odd warning message when the code contains C++ style comments (i.e. //)
For the most common error warnings that typically are bugs, the -Wall and -W options both should be used
GNU / Linux
Electrical and Communication Technology GCC & Make-20
GNU/Linux
Command Line Options
● Keep all temporary files (-save-temps)
● Show sub-command calls and other verbose messages (-v)
● Add symbol table to object / executable files for debugging (-g[x])
● Optimize the output to the assembly file (-O[x] capital letter o)
● Specify path to includes (-I capital letter i)
● Specify path to library archive files (-L)
● Specify a specific library to use when linking (-l small letter L)
GNU / Linux
Electrical and Communication Technology GCC & Make-21
GNU/Linux
Preprocessing (cpp command)● Equivalent commands:
$ gcc -E hello.c -o hello.i$ cpp hello.c > hello.i
● Processing: Removes macro definitions and expands (#define) Handles compiler conditional directives (#if/#elif/#else/#endif) Inserts header files recursively (#include) Removes comments ( /* */, // ) Adds line number and filename indications (#) Does not remove pragma directives (#pragma)
● Line number and file-name indications allow for accurate localization of warning and error messages identified during compilation step.
GNU / Linux
Electrical and Communication Technology GCC & Make-22
GNU/Linux
Compilation (i-File to s-File)● Command:$ gcc -S hello.i -o hello.s
● Processing: Parses preprocessed file Processes statements Optimizes (optional) Converts statements into assembly Outputs assembly file Prints warning and error messages
● Current GCC versions combine Preprocessing and Compilation steps into one integrated step
GNU / Linux
Electrical and Communication Technology GCC & Make-23
GNU/Linux
Assembly (as command)
● Equivalent commands:$ gcc -c hello.s -o hello.o$ as hello.s -o hello.o
● Processing: Parses assembly file Converts assembly to machine code Outputs object file
● External function calls and data are left with undefined references.
GNU / Linux
Electrical and Communication Technology GCC & Make-24
GNU/Linux
Linking (ld command)● Equivalent commands:$ gcc hello.o -o hello
● Processing: Reads input object files and static libraries Resolves undefined references Sets up any dynamic library references Links all the object files in order, as found on the command line Outputs the executable file Prints an error message if references can not be resolved
● If the native compiler (or cross compiler) was built correctly, there is no need to understand or remember the “ld” form of the command – just use the “gcc” command on the command line
GNU / Linux
Electrical and Communication Technology GCC & Make-25
GNU/Linux
Archive (ar command)• Bundles multiple object files into one static library file
• Example – create archive then use it:$ ar cr libsockio.a send.o receive.o$ gcc main.c libsockio.a -o talk
• Example – list archive’s table of contents:$ ar t libsockio.a
• Standard format for static library filename:lib<user_defined>.awhere <user_defined> is specified by the developer
• Any archive headers included by external source or other header files, need to be distributed with the static library file
GNU / Linux
Electrical and Communication Technology GCC & Make-26
GNU/Linux
Disassembly (objdump command)● Disassembles an object or executable file back into an assembly
file with optional interspersed source code● Example: $ gcc -g hello.c -o hello $ objdump -C -D -S -l hello > hello.disassembly
• Object or executable file must have been assembled (and linked) with debugging turned on (-g option) to include the interspersed source code.
• Helpful for understanding what exactly the compiler is doing• Inserted (interspersed) lines of source code before blocks of
assembly op-codes show what assembly was generated for specific C / C++ statements
• The best results of interspersed source code occur when optimization is turned off (-O0 option (capital letter o followed by zero)).
GNU / Linux
Electrical and Communication Technology GCC & Make-27
GNU/Linux
Disassembly outputappReadPoti: file format elf32-littlearm
Disassembly of section .interp:00008134 <.interp>: 8134: 62696c2f rsbvs r6, r9, #12032 ; 0x2f00 8138: 2d646c2f stclcs 12, cr6, [r4, #-188]! ; 0xffffff44 813c: 756e696c strbvc r6, [lr, #-2412]! ; 0x96c 8140: 72612d78 rsbvc r2, r1, #120, 26 ; 0x1e00 ...Disassembly of section .note.ABI-tag:
00008150 <.note.ABI-tag>:$d(): 8150: 00000004 andeq r0, r0, r4 8154: 00000010 andeq r0, r0, r0, lsl r0 8158: 00000001 andeq r0, r0, r1 815c: 00554e47 subseqr4, r5, r7, asr #28 816c: 00000001 andeq r0, r0, r1
GNU / Linux
Electrical and Communication Technology GCC & Make-28
GNU/Linux
Symbol Table Parsing (nm command)
• Lists the symbols in the object file’s or executable file’s symbol table
• Example:$ nm hello
• File must have been compiled (and linked) with debugging turned on (-g option)
• “nm” stands for name
• Useful for troubleshooting linking errors where a symbol is: defined in multiple object or library files referenced but not defined in any object or library file
GNU / Linux
Electrical and Communication Technology GCC & Make-29
GNU/Linux
Symbol Table Removal (strip command)
● Removes the symbol table from an object or executable file
● Example:$ strip hello
● Significantly shrinks the file size
● Useful after debugging is complete and the file is ready to be distributed
● Helps to limit reverse engineering of proprietary software
GNU / Linux
Electrical and Communication Technology GCC & Make-30
GNU/Linux
Debugging (gdb command)
• Supports the debugging of running code as well as diagnosis of core dump files
• Example to start and debug an executable:$ gdb -se=hello
• Example to debug a core file:$ gdb -s hello -c core
• GUI interfaces, such as eclipse, insight or DDD, offer a simplified user interface to gdb
GNU / Linux
Electrical and Communication Technology GCC & Make-31
GNU/Linux
Project Building using make
● Compiles the source code of a project and builds the executable(s)
● Example:$ make
● Builds only the files that are out of date
● Highly configurable
● Text based Makefile is used to specify build steps.
● Uses generic build rules, source specific steps, or a mix
GNU / Linux
Electrical and Communication Technology GCC & Make-32
GNU/Linux
Make Variables
● Variables are defined and used as follows: Definition: VAR = value Use: $(VAR) or ${VAR}
● Make uses various variables to define compile and link process: CC Compiler CFLAGS Compiler options INCLUDES directories to be searched for header files LDFLAGS Linker options
GNU / Linux
Electrical and Communication Technology GCC & Make-33
GNU/Linux
Make Rules
• Rules tell make how to compile or link
• Example:
file1.o : file1.c
$(CC) $(CFLAGS) file1.c
• This rule defines how to generate the file “file1.o”, calling the compiler defined in variable $(CC).
• Note that there is a tab starting the second line!
GNU / Linux
Electrical and Communication Technology GCC & Make-34
GNU/Linux
Make Targets (1)
● Targets have two important meanings: They tell make what to do
They define dependencies in the project
● Example:myprog : file1.o file2.o
$(CC) $(LDFLAGS) file1.o file2.o -o myprog
● Source and Object Files may be defined in variables, too
GNU / Linux
Electrical and Communication Technology GCC & Make-35
GNU/Linux
Make Targets (2)
● Often used targets are: all: compile and build all
test: start automatic tests
clean: remove object files, binaries and executables
install: install binaries and executables, e.g copy files to target dir
● Targets are started by calling:$ make <targetname>
GNU / Linux
Electrical and Communication Technology GCC & Make-36
GNU/Linux
A Simple Makefile
Variables
Dependencies
Compile source
Link project
Linker flags
Compiler flags
“make clean”, removes old files
executable
# cross compiler (CROSS_COMPILE set in /etc/profile)CC = ${CROSS_COMPILE}gcc
# compiler flags: debug symbols, all warningsCFLAGS = -mcpu=cortex-a8 -g -Wall
# Linker flagsLDFLAGS = -Wl, -Map=myprog.map
# Make rulesmyprog: myprog.o
$(CC) $(LDFLAGS) myprog.o -o myprog
myprog.o: myprog.c$(CC) $(CFLAGS) myprog.c
clean:rm -f *.o *~ myprog
GNU / Linux
Electrical and Communication Technology GCC & Make-37
GNU/Linux
Sample Make File for an Embbeded App (1)
# Embedded-Linux (BTE5446)# Set make enviroment variables for the target# Version: 1.0# File: make_env_target
export TARGET_ROOTFS = /opt/embedded/bbb/rootfsexport LOCAL_INC = $(TARGET_ROOTFS)/usr/local/includeexport LOCAL_LIB = $(TARGET_ROOTFS)/usr/local/libexport SYSTEM_INC = $(TARGET_ROOTFS)/usr/includeexport SYSTEM_LIB = $(TARGET_ROOTFS)/usr/libexport EXTRA_CFLAGS = -mcpu=cortex-a8
GNU / Linux
Electrical and Communication Technology GCC & Make-38
GNU/Linux
Sample Make File for an Embbeded App (2)# Include the platform (host or target) enviroments variables, make HOST=1ifdef HOST include make_env_hostelse include make_env_targetendif
# Tool names (tools rely on variable CROSS_COMPILE that is set in /etc/profile)AS = $(CROSS_COMPILE)asAR = $(CROSS_COMPILE)arCC = $(CROSS_COMPILE)gccCPP = $(CROSS_COMPILE)g++LD = $(CROSS_COMPILE)ldNM = $(CROSS_COMPILE)nmOBJCOPY = $(CROSS_COMPILE)objcopyOBJDUMP = $(CROSS_COMPILE)objdumpRANLIB = $(CROSS_COMPILE)ranlibREADELF = $(CROSS_COMPILE)readelfSIZE = $(CROSS_COMPILE)sizeSTRINGS = $(CROSS_COMPILE)stringsSTRIP = $(CROSS_COMPILE)stripexport AS AR CC CPP LD NM OBJCOPY OBJDUMP RANLIB READELF SIZE STRINGS STRIP
GNU / Linux
Electrical and Communication Technology GCC & Make-39
GNU/Linux
Sample Make File for an Embbeded App (3)
# Build settingsEXEC_NAME = appLinuxCFLAGS = ${EXTRA_CFLAGS} -g -gdwarf-2 -WallHEADER = -I${LOCAL_INC} -I${SYSTEM_INC}LIBS = -lmLDFLAGS= $(LIBS) -Wl,-Map=${EXEC_NAME}.map -L${LOCAL_LIB} -L${SYSTEM_LIB}
# Installation variablesINSTALL = installINSTALL_DIR = ${TARGET_ROOTFS}/usr/local/bin
# Files needed for the buildOBJS = ${EXEC_NAME}.o
# Make rulesall: ${EXEC_NAME}
GNU / Linux
Electrical and Communication Technology GCC & Make-40
GNU/Linux
Sample Make File for an Embbeded App (4)
${EXEC_NAME} : $(OBJS)$(CC) -o $(EXEC_NAME) ${OBJS} $(LDFLAGS)
%.o: %.c$(CC) -c $(HEADER) $(CFLAGS) $<
install: ${EXEC_NAME}test -d $(INSTALL_DIR) || $(INSTALL) -d -m 755 $(INSTALL_DIR)$(INSTALL) -m 755 $(EXEC_NAME) $(IMAGES) $(INSTALL_DIR)
GNU / Linux
Electrical and Communication Technology GCC & Make-41
GNU/Linux
Sample Make File for an Embbeded App (5)asm:
@if [ -a $(EXEC_NAME) ]; then arm-linux-objdump -C -D -S -l \$(EXEC_NAME) > $(EXEC_NAME).S; \
else echo "You must first run make!"; fi;
doc:doxygen
clean:rm -f *.o $(EXEC_NAME)
distclean:rm -f *.Srm -f *.maprm -f *.o $(EXEC_NAME) rm -r doc
GNU / Linux
Electrical and Communication Technology GCC & Make-42
GNU/Linux
Profiling (gprof command)• Analyzes the processing time for each function in an
executable
• Three step technique: Compiler adds additional code to “instrument” the executable Collect the timing data by running the executable Use gprof tool to report the function timing
• Example:
$ gcc -pg hello.c -o hello
hello (creates the file gmon.out)
gprof hello
GNU / Linux
Electrical and Communication Technology GCC & Make-43
GNU/Linux
Profiling (gprof command)● Both compiler and linker must receive the profiler command line
option (-pg)● Instrumented executable generates a gmon.out file containing
data related to the function timing.● Useful when looking to improve the performance of an
executable● The best effort to optimize code should concentrate on the
functions that use the largest percentage of processor time.● Also gives information on the function call sequence● Example outputEach sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls Ts/call Ts/call name 100.00 0.97 0.97 func
GNU / Linux
Electrical and Communication Technology GCC & Make-45
GNU/Linux
Coverage Testing (gcov command)● Analyzes which source lines of code have been executed or “covered”
● Three step technique: Compiler adds additional code to “instrument” the executable Collect the coverage data by running the executable Use gcov tool to report the number of times each line was
executed
● Example:
$ gcc -fprofile-arcs -ftest-coverage hello.c -o hello
$ hello
$ gcov hello.c
GNU / Linux
Electrical and Communication Technology GCC & Make-46
GNU/Linux
Coverage Testing (gcov command)● Configure the kernel with: CONFIG_DEBUG_FS=y CONFIG_GCOV_KERNEL=y
and to get coverage data for the entire kernel: CONFIG_GCOV_PROFILE_ALL=y
● Note that kernels compiled with profiling flags will be significantly larger and run slower.
● Also CONFIG_GCOV_PROFILE_ALL may not be supported on all architectures.
● Profiling data will only become accessible if debugfs has been mounted:
$ mount -t debugfs none /sys/kernel/debug
GNU / Linux
Electrical and Communication Technology GCC & Make-47
GNU/Linux
Coverage Testing (gcov command)
● Analyzes which source lines of code have been executed or “covered”
● Three step technique: Compiler adds additional code to “instrument” the executable Collect the coverage data by running the executable Use gcov tool to report the number of times each line was executed
● Example:
$ gcc -fprofile-arcs -ftest-coverage hello.c -o hello
$ hello
$ gcov hello.c
GNU / Linux
Electrical and Communication Technology GCC & Make-48
GNU/Linux
Coverage Testing (gcov command)
• gcov creates a file (hello.c.gcov) containing an annotated version of the source code. The first column contains a count of how many times each line was executed.
• In *.gcov files, the lines beginning with “#####” were not executed.
• The gcov feature helps:
Find some bugs in branching code (i.e. “if” statements)
Assist testing of the code Optimize code based on the likelihood that a branch is taken
GNU / Linux
Electrical and Communication Technology GCC & Make-49
GNU/Linux
Coverage Testing (gcov command)
● User Interface Because gcov only creates ASCII text files, the latest stage was to use some parsing tools to generate human readable reports.
lcov automates the process of extracting the coverage data using Gcov and producing HTML results based on that data.
GNU / Linux
Electrical and Communication Technology GCC & Make-51
GNU/Linux
Conclusions● GNU GCC offers many features and is the closest
development system to being universal that exists(allows more familiarity over time, thus improving productivity).
● Strong current support translates to high probability of GCC being supported in the distant future.
● GUI’s and IDE’s like DDD and Eclipse offer more intuitive interfaces.
● Its FREE
The price is right.
If you don’t like it, you can fix it and give it to everyone else.
GNU / Linux
Electrical and Communication Technology GCC & Make-52
GNU/Linux
Reference Books (1/4)
• An Introduction to GCC
by Brian J. Gough, foreword by Richard M. StallmanPaperback (6"x9"), 144 pages. Revised August 2005.Retail Price: $19.95 (£12.95 in UK)ISBN: 0-9541617-9-3
GNU / Linux
Electrical and Communication Technology GCC & Make-53
GNU/Linux
Reference Books (2/4)• Using GCC
➢ By Richard M. Stallman, GCC Developer Community
➢ Copyright 2003 Free Software Foundation, Inc.
➢ Published by GNU Press➢ Official reference manual of GCC➢ The above hardcopy book is for GCC
Version 3.3.1.➢ Amazon.com sells it new for $45.00.➢ Online access
(current documentation of current software) http://gcc.gnu.org/onlinedocs/gcc/
GNU / Linux
Electrical and Communication Technology GCC & Make-54
GNU/Linux
Reference Books (3/4)
• Debugging with GDB➢ By Richard M. Stallman, Roland H.
Pesch, and Stan Shebs➢ Copyright 2003 Free Software
Foundation, Inc.➢ Published by GNU Press➢ The GNU source-level debugger
GNU / Linux
Electrical and Communication Technology GCC & Make-55
GNU/Linux
Reference URL’s
• GCC, the GNU Compiler Collection (main web site)➢ http://gcc.gnu.org/
• Many documents of different subcategories of GCC and different versions of GCC
➢ http://gcc.gnu.org/onlinedocs/
• GNU's Not Unix! (GNU)➢ http://www.gnu.org/
• Free Software Foundation (FSF)➢ http://www.fsf.org/
● linux-3.x/Documentation