Search code examples
c++global-variablesavr32-gcc

avr32-gcc: Global variable not initialized with function output


I try to initialize a global variable with the output of a function. It works as expected for gnu-gcc, but when compiled with avr32-gcc, the variable is initialized with 0. I want the variable to be initialized by a function since in the real scenario it is a reference (MyClass& myclass = MyClass::getInstance().

Here is the code:

extern "C"
{
    #include "led.h"
}

int getInteger() 
{
    return 10;
}

int my_int = getInteger();

int main (void)
{
    LED_On(LED2);

    //my_int = getInteger();    //* This line really sets my_int = 10;

    if(my_int == 10)
    {
        LED_On(LED1);
    }

    while(1){
        __asm__ ("nop");            
    }

    return 0;
}

and here is my Makefile:

PROJ_NAME=TEST

# Include paths for project folder
SRCS_INC += -I. -I./preprocessor

# Sources files for project folder (*.c and *.cpp)
SRCS += main.cpp exception_noNMI.S startup_uc3.S trampoline_uc3.S intc.c led.c

AS = avr32-gcc
ASFLAGS = -x assembler-with-cpp -c -mpart=uc3c1512c -mrelax 
ASFLAGS += ${SRCS_INC}

CC = avr32-gcc 
CFLAGS += -mpart=uc3c1512c
CFLAGS += ${SRCS_INC}

CXX = avr32-g++

LINKER = avr32-g++
OBJCOPY = avr32-objcopy

LDFLAGS  = -nostartfiles -mpart=uc3c1512c
LDFLAGS += ${SRCS_INC}

OBJS += $(addsuffix .o, $(basename $(SRCS)))

# Main rule
all: $(PROJ_NAME).elf

# Linking
${PROJ_NAME}.elf: ${OBJS}
    @echo Linking...
    @$(CXX) $(LDFLAGS) $^ -o $@  
    @$(OBJCOPY) -O ihex ${OBJCOPYFLAGS} $(PROJ_NAME).elf $(PROJ_NAME).hex
    @$(OBJCOPY) -O binary $(PROJ_NAME).elf $(PROJ_NAME).bin

# Assembly files in source folder
%.o: ./%.S
    @mkdir -p $(dir $@)
    @$(AS) $(ASFLAGS) -c $< -o $@

# C files in source folder
%.o: ./%.c
    @mkdir -p $(dir $@)
    @$(CC) -c $< -o $@ $(CFLAGS)

# CPP files in SRC folder
%.o: ./%.cpp
    @mkdir -p $(dir $@)
    @$(CXX) -c $< -o $@ $(CFLAGS)

.PHONY: clean
clean:
    @rm -f $(OBJS) $(PROJ_NAME).elf $(PROJ_NAME).hex $(PROJ_NAME).bin

I also tried to make an init function with __attribute(constructor) as explained in this answer. Still it is not excuted.


Solution

  • As far as I can see, you're not having optimization enabled. Thus, the compiler may actually make a call to getInteger during startup. Now, you're replacing the default startup with something that you do not show. Maybe you just need to make sure that this is done during startup? Also, you could try to enable optimization and see if the call is resolved.