关于动态内存分配示例在新编译器(WINAVR20070101)中无法编译的解决方法:
主要问题是I/O流初始化在新版编译器中的改进。
一。定义__STDIO_FDEVOPEN_COMPAT_12,使新版本与旧版本一样的方式编译源程序的改动如下:
#include "avr/io.h"
#define __STDIO_FDEVOPEN_COMPAT_12
#include "stdio.h"
#include "stdlib.h"
编译后输出结果如下:
-------- begin --------
avr-gcc (GCC) 4.1.1 (WinAVR 20070101)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Compiling: main.c
avr-gcc -c -mmcu=atmega8 -I. -gstabs -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst -std=gnu99 -Wp,-M,-MP,-MT,main.o,-MF,.dep/main.o.d main.c -o main.o
Linking: main.elf
avr-gcc -mmcu=atmega8 -I. -gstabs -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.o -std=gnu99 -Wp,-M,-MP,-MT,main.o,-MF,.dep/main.elf.d main.o --output main.elf -Wl,-Map=main.map,--cref -Wl,-u,vfprintf -lprintf_min -Wl,-u,vfscanf -lscanf_min -lm
Creating load file for Flash: main.bin
avr-objcopy -O binary -R .eeprom main.elf main.bin
Creating load file for Flash: main.hex
avr-objcopy -O ihex -R .eeprom main.elf main.hex
Creating load file for EEPROM: main.eep
avr-objcopy -j .eeprom --set-section-flags=.eeprom="alloc,load" \
--change-section-lma .eeprom=0 -O ihex main.elf main.eep
Creating Extended Listing: main.lss
avr-objdump -h -S main.elf > main.lss
Creating Symbol Table: main.sym
avr-nm -n main.elf > main.sym
Size after:
text data bss dec hex filename
3354 28 266 3648 e40 main.elf
Errors: none
-------- end --------
二。使用新的方法初始化I/O流。
下面是用新方式使用I/O流的示例,没有测试于硬件上,但编译通过。
/*
动态内存分配测试程序
文件名:main.c
硬件:CA-M8
时钟:外部4MHz
2004-11-28
*/
#include "avr/io.h"
#include "stdio.h"
#include "stdlib.h"
char g_aMemory[256];
static int uart_putchar(char c, FILE *stream);
static int uart_getchar( FILE *stream);
static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, uart_getchar,_FDEV_SETUP_RW);
static int uart_putchar(char c, FILE *stream)
{
if (c == '\n')
uart_putchar('\r', stream);
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
static int uart_getchar( FILE *stream)
{
loop_until_bit_is_set(UCSRA,RXC);
return UDR;
}
void IoInit(void)
{
//UART初始化
UCSRB=_BV(RXEN)|_BV(TXEN);
UBRRL=25; //9600 baud 6MHz:38 4MHz:25
}
int main(void)
{
char *p;
int i;
char c;
IoInit();
// __malloc_heap_start=g_aMemory;
// __malloc_heap_end=g_aMemory+256;
while(1)
{
p=malloc(100);
if(p!=0)
{
for(i=0;i<100;i++)
p[i]=i;
for(i=0;i<100;i++)
printf("%d\n",p[i]);
free(p);
}
else
printf("分配内存失败!");
scanf("%c",&c);
}
}
|
|