怎么这个编译成4kb?

时间:2013-10-09 04:22:34

标签: c optimization avr avr-gcc

#define F_CPU 1000000

#include <stdint.h>
#include <avr/io.h>
#include <util/delay.h>

const uint8_t sequences[] = {
    0b00000001, 
    0b00000011,
    0b00000110,
    0b00001100,
    0b00011000,
    0b00110000,
    0b00100000,
    0b00110000,
    0b00011000,
    0b00001100,
    0b00000110,
    0b00000011,
    0b00000001,
};

const uint8_t totalSequences = sizeof(sequences) / sizeof(sequences[0]);

int main(void) {
    DDRB = 0b00111111;

    uint8_t i;
    uint8_t b;

    while(1) {
        for(i = 0; i < totalSequences; i++) {
            const uint8_t currentSequence = sequences[i];
            const uint8_t nextSequence = sequences[(i + 1) % totalSequences];

            // blend between sequences
            for(b = 0; b < 100; b++) {
                PORTB = currentSequence;  _delay_us(b);
                PORTB = nextSequence;     _delay_us(100-b);
            }

            _delay_ms(50);
        }
    }

    return 0;
}

这是我整个程序。当我直接设置PORTB(没有混合)时,编译的二进制文件是214个字节。当我包含第二个for循环时,我编译的二进制文件超过4kb。我只有1kb的FLASH,所以我需要把它放在那里。

const uint8_t currentSequence = sequences[i];
const uint8_t nextSequence = sequences[(i + 1) % totalSequences];

//// blend between sequences
//for(b = 0; b < 100; b++) {
//  PORTB = currentSequence;  _delay_us(b);
//  PORTB = nextSequence;     _delay_us(100-b);
//}

PORTB = currentSequence;
PORTB = nextSequence;
_delay_ms(50);

我的工具链是WINAVR,使用以下代码编译:

avr-gcc -Os -mmcu=attiny13 -Wall -std=c99 main.c -o main.out
avr-objcopy -O binary main.out main.bin

我不知道反编译二进制文件并看看编译器做了什么,但不管它是什么,都是错误的。为什么二进制内部循环为4kb,以及如何修复它?

修改循环(278字节):

while(1) {
    for(i = 0; i < totalSequences; i++) {
        const uint8_t currentSequence = sequences[i];
        const uint8_t nextSequence = sequences[(i + 1) % totalSequences];

        // blend between sequences
        for(b = 0; b < 100; b++) {
            int d;
            PORTB = currentSequence;  for(d = 0; d < b; d++,   _delay_us(1));
            PORTB = nextSequence;     for(d = 100; b < d; d--, _delay_us(1));
        }

        _delay_ms(50);
    }
}

1 个答案:

答案 0 :(得分:3)

delay()函数会破坏代码大小,除非参数是编译时常量。它也不会延迟使用可变参数的正确时间。