Помощь - Поиск - Пользователи - Календарь
Полная версия этой страницы: uint24_t
Форум разработчиков электроники ELECTRONIX.ru > Микроконтроллеры (MCs) > Cредства разработки для МК > GNU/OpenSource средства разработки
Злодей
Бутлодер для mega128 малость не влезает в 2k флэша, а нужно впихнуть. Первое что приходит в голову - бороться с flash_size_t, который у меня из-за RAMP_Z для atmega128+ определен как uint32_t...

Откуда взять uint24_t? Если сделать структуру из трёх байт, и написать функции арифметических действий над ней, будет профит?
demiurg_spb
Цитата(Злодей @ Jan 26 2010, 12:19) *
Если сделать структуру из трёх байт, и написать функции арифметических действий над ней, будет профит?
Если функции напишешь на asm, то, возможно, будет. Всё зависит от кол-ва данных типа uint32_t и активности операций над ними.
Правда исходники будут выглядеть не очень читабельно, но не писать же бут на C++ с перегрузкой операторов для типа uint24_t:)
Сергей Борщ
Цитата(Злодей @ Jan 26 2010, 11:19) *
Бутлодер для mega128 малость не влезает в 2k флэша, а нужно впихнуть.
1) Есть множество ключей компиляции, игры с которыми позволяют уменьшить код.
2) Попробуйте самый свежий WinAVR 20100110 - в нем сильно оптимизирована работа с eeprom.
3) Также очень помогает встраивание функций, вызываемых один раз.
4) Можно оптимизировать сам исходник. AVR231 у меня влез в 2К с запасом.

Вот мои ключи:
Код
CFLAGS += -ffunction-sections
CFLAGS += -fdata-sections

# code optimisation
CFLAGS += -fno-ivopts
#CFLAGS += -mcall-prologues
#CFLAGS += -fno-tree-scev-cprop
#CFLAGS += -fno-split-wide-types
#CFLAGS += -fno-inline-small-functions

CFLAGS += --param inline-call-cost=0  <- это число подобрать.
#CFLAGS += -fno-reorder-blocks
#CFLAGS += -fno-reorder-blocks-and-partition
#CFLAGS += -fno-reorder-functions
#CFLAGS += -fno-toplevel-reorder
CFLAGS += -fno-move-loop-invariants
#CFLAGS += -fno-unroll-loops
#CFLAGS += -fno-unroll-all-loops
#CFLAGS += --param max-unroll-times=0

LDFLAGS += -Wl,--gc-sections
LDFLAGS += -Wl,--relax
попробуйте раскомментировать/закомментировать некоторые из них.
demiurg_spb
Цитата(Сергей Борщ @ Jan 26 2010, 13:16) *
Вот мои ключи...
Есть такой ключ, что всем ключам ключ:
Код
CFLAGS += --combine
CFLAGS += -fwhole-program
Сергей Борщ
Цитата(demiurg_spb @ Jan 27 2010, 12:37) *
Есть такой ключ, что всем ключам ключ:
Код
CFLAGS += --combine
CFLAGS += -fwhole-program
Вчера потратил 2 часа, пытаясь собрать с его помощью первый попавшийся проект на С++. Так и не удалось. Ругался undefined variable на все глобальные объекты и переменные. Без этого ключа все собирается и работает.
demiurg_spb
Using the GNU Compiler Collection. For gcc version 4.3.4
Цитата
-fwhole-program
Assume that the current compilation unit represents whole program being compiled. All public functions and variables with the exception of main and those
merged by attribute externally_visible become static functions and in a affect gets more aggressively optimized by interprocedural optimizers. While this option is equivalent to proper use of static keyword for programs consisting of single file, in combination with option ‘--combine’ this flag can be used to compile most of smaller scale C programs since the functions and variables become local for the whole combined compilation unit, not for the single source file itself.This option is not supported for Fortran programs.

-combine
If you are compiling multiple source files, this option tells the driver to pass all the source files to the compiler at once (for those languages for which the compiler can handle this). This will allow intermodule analysis (IMA) to be performed by the compiler. Currently the only language for which this is supported is C. If you pass source files for multiple languages to the driver, using this option, the driver will invoke the compiler(s) that support IMA once each, passing each compiler all the source files appropriate for it. For those languages that do not support IMA this option will be ignored, and the compiler will be invoked once for each source file in that language. If you use this option in conjunction with -save-temps, the compiler will generate multiple pre-processed files (one for each source file), but only one (combined) .o or .s file.
Сергей Борщ
Цитата(demiurg_spb @ Jan 27 2010, 14:00) *
Currently the only language for which this is supported is C
Да читал я это... Подумал - если он не выругался на неправильный язык, то может просто документацию не подправили... Причем в листинге все корректно, переменные есть.
demiurg_spb
Цитата(Сергей Борщ @ Jan 27 2010, 15:30) *
Подумал - если он не выругался на неправильный язык, то может просто документацию не подправили...
Всё может быть...
У нас на pure-C проекте отлично работает (бутлоадер кстати).
Злодей
Цитата(Сергей Борщ @ Jan 27 2010, 13:52) *
Вчера потратил 2 часа, пытаясь собрать с его помощью первый попавшийся проект на С++. Так и не удалось. Ругался undefined variable на все глобальные объекты и переменные. Без этого ключа все собирается и работает.

Ключ ломает стереотипы. Отпадают цели вроде "$(OBJDIR)/%.o : %.c", т.к. по одному они компилиться не могут больше.
# Compile: create object files from C source files.
# $(OBJDIR)/%.o : %.c
# @echo
# @echo $(MSG_COMPILING) $<
# $(CC) -c $(ALL_CFLAGS) $< -o $@


compile:
$(CC) $(CFLAGS) $(CDEFS) $(LDFLAGS) $(SRC) -o $(TARGET).elf


...Или дело даже не в этом, а в том, что у Вас C++?
ARV
Цитата(Злодей @ Jan 28 2010, 12:51) *
Ключ ломает стереотипы. Отпадают цели вроде "$(OBJDIR)/%.o : %.c", т.к. по одному они компилиться не могут больше.
это точно... я все старался прикрутить эти ключики к автоматически генерируемому makefile в среде Eclipse - потерпел неудачу... там пофайловое компилирование. придется привыкать к hand-made makefiles smile.gif
_Pasha
Цитата(ARV @ Jan 28 2010, 13:04) *
придется привыкать к hand-made makefiles smile.gif

Лучше не отвыкать. Ну, эклипса - ладно, но остальные (Avrstudio gcc plugin, Code Blocks) - иногда такое выстегивают, что лучше ими не пользоваться
Сергей Борщ
Цитата(Злодей @ Jan 28 2010, 11:51) *
Ключ ломает стереотипы.
Не, ну доку-то я первым делом прочитал. Конечно все файлы компилились скопом.
Цитата(Злодей @ Jan 28 2010, 11:51) *
...Или дело даже не в этом, а в том, что у Вас C++?
Да. Провел элементарный эксперимент:
Код
main.cpp:
#include    <avr/io.h>

volatile int a;
extern void test();

int main()
{
    for(;;)
    {
        PORTB = a;
        test();
    }
}

test.cpp:
#include    <avr/io.h>

extern volatile int a;

void test()
{
    PORTC = a;
}
avr-gcc -mmcu=atmega8 --combine -fwhole-program main.cpp test.cpp -o main.elf

D:\Temp/ccEyCFtV.o: In function `main':
main.cpp:(.text+0x16): undefined reference to `test()'
Переименовываю файлы в *.c - все компилится.
Можно предположить, что ему сносит крышу от плюсового name mangling.
ReAl
Цитата(Злодей @ Jan 28 2010, 11:51) *
Ключ ломает стереотипы.
Стереотипы он ломает в другом месте. У тех, у которых они были - про то, что "если вызывается функция из другого файла, то и компилятор не переставит операции в коде, и volatile можно не ставить".
singlskv
Цитата(ReAl @ Jan 28 2010, 17:50) *
Стереотипы он ломает в другом месте. У тех, у которых они были - про то, что "если вызывается функция из другого файла, то и компилятор не переставит операции в коде, и volatile можно не ставить".
А разьве это(сваливание всего в кучу) просто не противоречит стандарту ?
Кажись именно за это ругали CodeVision...

По-моему тот кто "вызывается функция из другого файла... , и volatile можно не ставить" все же точно знает что он делает и почему...
Я не агитирую за то что так нужно делать всегда, это несомненно плацдарм для "скрытых" ошибок,
но иногда этим сам пользуюсь когда нужно чего-нить дооптимизировать...
SysRq
Убрать таблицу векторов прерываний, если не нужна (или сократить, вручную создав нужные вектора).
Если избавиться от глобальных и локальных static данных (или в .noinit их), то оптимизируется долой __do_clear_bss из стартапа - это еще немного байт smile.gif
SysRq
Ежели кого не сильно затруднит, выложите пожалуйста правильный Makefile с этими ключами:
Код
CFLAGS += --combine
CFLAGS += -fwhole-program

Я что-то страшное сотворил, никак не пойму где наврал wacko.gif . Получаю множество:
Цитата
In file included from main.h:10:
c:/winavr/lib/gcc/../../avr/include/avr/interrupt.h:38:20: error: calling fdopen: No such file or directory
demiurg_spb
Это мой Makefile для проекта из соседнего топика про сравнение gcc и iar.
CODE
#----------------------------------------------------------------------------
# Programmer type:
#----------------------------------------------------------------------------
PROGRAMMER = DUDE
#PROGRAMMER = REAL
#PROGRAMMER = BOOT

#----------------------------------------------------------------------------
PROJECT_NAME = monitor-gcc

COMPILE_NAME = test
MCU = atmega8
F_CPU = 4608000
#----------------------------------------------------------------------------

COMPILE_NAME := $(PROJECT_NAME)$(COMPILE_NAME)
DEVICE_ID = 3
DEVICE_REV = $(COMPILE_TYPE)
MAIN_BINDIR = ./bin
BINDIR = $(MAIN_BINDIR)/$(COMPILE_NAME)
TARGET = $(BINDIR)/$(PROJECT_NAME)

#----------------------------------------------------------------------------
ADD_COMPILE_FLAGS += -DPROJECT_NAME=$(PROJECT_NAME)


#----------------------------------------------------------------------------
# Output format. (can be srec, ihex, binary)
FORMAT = ihex

# Object files directory
# To put object files in current directory, use a dot (.), do NOT make
# this an empty or blank macro!
OBJDIR = $(MAIN_BINDIR)./../obj
DEPDIR = $(OBJDIR)/dep

# List source directories here:
SOURCE_DIRS = .
VPATH := $(SOURCE_DIRS)


# List C source files here. (C dependencies are automatically generated.)
SRC = hal.c
SRC += app.c
SRC += lcd4.c
SRC += main.c

# Optimization level, can be [0, 1, 2, 3, s].
# 0 = turn off optimization. s = optimize for size.
# (Note: 3 is not always the best optimization level. See avr-libc FAQ.)
OPT = s


# Debugging format.
# Native formats for AVR-GCC's -g are dwarf-2 [default] or stabs.
# AVR Studio 4.10 requires dwarf-2.
# AVR [Extended] COFF format requires stabs, plus an avr-objcopy run.
DEBUG = dwarf-2

# Compiler flag to set the C Standard level.
# c89 = "ANSI" C
# gnu89 = c89 plus GCC extensions
# c99 = ISO C99 standard (not yet fully implemented)
# gnu99 = c99 plus GCC extensions
CSTANDARD = -std=c99
#CSTANDARD = -std=gnu99


# Place -D or -U options here for C sources
CDEFS = -DF_CPU=$(F_CPU)UL


#---------------- Compiler Options C ----------------
# -g*: generate debugging information
# -O*: optimization level
# -f...: tuning, see GCC manual and avr-libc documentation
# -Wall...: warning level
# -Wa,...: tell GCC to pass this to the assembler.
# -adhlns...: create assembler listing
CFLAGS = -g$(DEBUG)
CFLAGS += $(CDEFS)
CFLAGS += -O$(OPT)
CFLAGS += -pedantic
CFLAGS += -funsigned-char
CFLAGS += -funsigned-bitfields
CFLAGS += -fpack-struct
CFLAGS += -fshort-enums
CFLAGS += -Wall
CFLAGS += -Wstrict-prototypes
CFLAGS += -fno-split-wide-types

CFLAGS += --combine
CFLAGS += -fwhole-program

CFLAGS += -ffunction-sections
CFLAGS += -fdata-sections
CFLAGS += -Wl,--relax

#************************************************
#CFLAGS += -fno-ivopts
CFLAGS += -ftree-loop-ivcanon
CFLAGS += -mcall-prologues

#CFLAGS += -ffreestanding

CFLAGS += -fno-tree-scev-cprop
CFLAGS += -finline-small-functions
CFLAGS += -fearly-inlining

#CFLAGS += --param inline-call-cost=0
CFLAGS += -finline-limit=65535

#CFLAGS += -fno-reorder-blocks
#CFLAGS += -fno-reorder-blocks-and-partition
#CFLAGS += -fno-reorder-functions
#CFLAGS += -fno-toplevel-reorder

#CFLAGS += -fno-move-loop-invariants

#CFLAGS += -fno-unroll-loops
#CFLAGS += -fno-unroll-all-loops
#CFLAGS += --param max-unroll-times=0
#************************************************


CFLAGS += -mshort-calls
CFLAGS += -fno-unit-at-a-time
#CFLAGS += -Wundef
#CFLAGS += -Wunreachable-code
CFLAGS += -Wsign-compare
CFLAGS += -Wa,-adhlns=$(TARGET).lst
CFLAGS += $(CSTANDARD)
CFLAGS += $(ADD_COMPILE_FLAGS)
CFLAGS += $(addprefix -I, $(SOURCE_DIRS))

#---------------- Library Options ----------------
# Minimalistic printf version
PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min

# Floating point printf version (requires MATH_LIB = -lm below)
PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt


# If this is left blank, then it will use the Standard printf version.
#PRINTF_LIB =
PRINTF_LIB = $(PRINTF_LIB_MIN)
#PRINTF_LIB = $(PRINTF_LIB_FLOAT)


# Minimalistic scanf version
SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min

# Floating point + %[ scanf version (requires MATH_LIB = -lm below)
SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt

# If this is left blank, then it will use the Standard scanf version.
#SCANF_LIB =
#SCANF_LIB = $(SCANF_LIB_MIN)
#SCANF_LIB = $(SCANF_LIB_FLOAT)


#MATH_LIB = -lm
MATH_LIB =


# List any extra directories to look for libraries here.
# Each directory must be seperated by a space.
# Use forward slashes for directory separators.
# For a directory that has spaces, enclose it in quotes.
EXTRALIBDIRS =



#---------------- Linker Options ----------------
# -Wl,...: tell GCC to pass this to linker.
# -Map: create map file
# --cref: add cross reference to map file
LDFLAGS =
LDFLAGS += -Wl,-Map=$(TARGET).map,--cref
#LDFLAGS += -Wl,-static -fvtable-gc -fdata-sections -ffunction-sections -Wl,--gc-sections -Wl,-s
LDFLAGS += -Wl,--gc-section

LDFLAGS += $(EXTMEMOPTS)
LDFLAGS += $(patsubst %,-L%,$(EXTRALIBDIRS))
LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)
#LDFLAGS += -T linker_script.x




#============================================================================
# Define programs and commands.
SHELL = sh
CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
SIZE = avr-size
AR = avr-ar rcs
NM = avr-nm
REMOVE = rm -f
REMOVEDIR = rm -rf
COPY = cp
WINSHELL = cmd


# Define Messages
# English
MSG_ERRORS_NONE = Errors: none
MSG_BEGIN = -------- begin --------
MSG_END = -------- end --------
MSG_SIZE_BEFORE = Size before:
MSG_SIZE_AFTER = Size after:
MSG_COFF = Converting to AVR COFF:
MSG_EXTENDED_COFF = Converting to AVR Extended COFF:
MSG_FLASH = Creating load file for Flash:
MSG_EEPROM = Creating load file for EEPROM:
MSG_EXTENDED_LISTING = Creating Extended Listing:
MSG_SYMBOL_TABLE = Creating Symbol Table:
MSG_BUILDING = Building project:
MSG_CLEANING = Cleaning project:

# Compiler flags to generate dependency files.
GENDEPFLAGS = -MMD -MP -MF $(TARGET).dep

# Combine all necessary flags and optional flags.
# Add target processor to flags.
ALL_CFLAGS = -mmcu=$(MCU) $(GENDEPFLAGS) $(CFLAGS)


# Default target.
all: begin gccversion sizebefore build sizeafter end

# Change the build target to build a HEX file or a library.
build: elf hex eep lss sym

elf: $(TARGET).elf
hex: $(TARGET).hex
eep: $(TARGET).eep
lss: $(TARGET).lss
sym: $(TARGET).sym


# Eye candy.
# AVR Studio 3.x does not check make's exit code but relies on
# the following magic strings to be generated by the compile job.
begin:
@echo
@echo $(MSG_BEGIN)

end:
@echo Device id_rev_opt: $(BOOT_HARDWARE_ID_HEX)
@echo $(MSG_END)
@echo


# Display size of file.
HEXSIZE = $(SIZE) --mcu=$(MCU) --target=$(FORMAT) $(TARGET).hex
ELFSIZE = $(SIZE) --mcu=$(MCU) --format=avr $(TARGET).elf

sizebefore:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); \
2>/dev/null; echo; fi

sizeafter:
@if test -f $(TARGET).elf; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); \
2>/dev/null; echo; fi


# Display compiler version information.
gccversion :
@$(CC) --version




# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB.
COFFCONVERT = $(OBJCOPY) --debugging
COFFCONVERT += --change-section-address .data-0x800000
COFFCONVERT += --change-section-address .bss-0x800000
COFFCONVERT += --change-section-address .noinit-0x800000
COFFCONVERT += --change-section-address .eeprom-0x810000



coff: $(TARGET).elf
@echo
@echo $(MSG_COFF) $(TARGET).cof
$(COFFCONVERT) -O coff-avr $< $(TARGET).cof


extcoff: $(TARGET).elf
@echo
@echo $(MSG_EXTENDED_COFF) $(TARGET).cof
$(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof



# Create final output files (.hex, .eep) from ELF output file.
%.hex: %.elf
@echo
@echo $(MSG_FLASH) $@
$(OBJCOPY) -O $(FORMAT) -R .eeprom -R .fuse -R .lock -R .signature $< $@

%.eep: %.elf
@echo
@echo $(MSG_EEPROM) $@
-$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 --no-change-warnings -O $(FORMAT) $< $@ || exit 0


# Create extended listing file from ELF output file.
%.lss: %.elf
@echo
@echo $(MSG_EXTENDED_LISTING) $@
$(OBJDUMP) -h -S $< > $@

# Create a symbol table from ELF output file.
%.sym: %.elf
@echo
@echo $(MSG_SYMBOL_TABLE) $@
$(NM) -n $< > $@

# Compile and Link whole program at time: create ELF output file from src files.
%.elf: $(SRC)
@echo
@echo $(MSG_BUILDING) $@
@echo
$(CC) $(ALL_CFLAGS) $^ --output $@ $(LDFLAGS)


#$(NAME).elf : $(CSRC)
# @echo $^
# @$(CC) -c $(CFLAGS) -combine -fwhole-program $^ $(LDFLAGS) -o $@



#=============================================================================
# Programmer section (ISP) :
#=============================================================================

ifeq ($(PROGRAMMER),DUDE)
include MakeProgDude.mak
endif

ifeq ($(PROGRAMMER),REAL)
include MakeProgReal.mak
endif

ifeq ($(PROGRAMMER),BOOT)
include MakeProgBoot.mak
endif

#=============================================================================
# Clean section:
#=============================================================================

clean: begin clean_list end

clean_list :
@echo
@echo $(MSG_CLEANING)
$(REMOVE) $(TARGET).cof
$(REMOVE) $(TARGET).elf
$(REMOVE) $(TARGET).map
$(REMOVE) $(TARGET).sym
$(REMOVE) $(TARGET).lss
$(REMOVE) $(TARGET).lst
$(REMOVE) $(TARGET).dep

# Create binary files directory
include $(shell mkdir $(MAIN_BINDIR) 2>/dev/null) $(shell mkdir $(BINDIR) 2>/dev/null)


# Listing of phony targets.
.PHONY : all begin finish end sizebefore sizeafter gccversion \
build elf hex eep lss sym coff extcoff program \
clean clean_list
Для просмотра полной версии этой страницы, пожалуйста, пройдите по ссылке.
Invision Power Board © 2001-2025 Invision Power Services, Inc.