g++ compiler removes global variable (residing in user defined section) from object file when opt level >= O1

Asked by Mallikarjun

Hi,
I have following test case, where a global variable (InterruptVector) is placed into a user defined section ".vect_table".

file: test.c :
#if __cplusplus
extern "C" {
#endif
extern int glob;
void test(void);
#if __cplusplus
}
#endif

void (* const InterruptVector[])() __attribute__ ((section(".vect_table"))) = {
 0,
 0,
 0,
 0,
 0
};

void test()
{
 glob++;
}

when i compile test.c with following command:
arm-none-eabi-g++ test.c -mcpu=cortex-m0 -mthumb -mfloat-abi=soft -c -O0
variable "InterruptVector" is retained in the object file.
if i use -O1, this variable gets removed from the obj file.

Is this expected behavior. How do i retain the global variable at opt levels >= -O1
Please let me know. Thanks for your time.

I used gcc 4.7.3.

regards,
Mallikarjuna

Question information

Language:
English Edit question
Status:
Solved
For:
GNU Arm Embedded Toolchain Edit question
Assignee:
No assignee Edit question
Solved by:
Thomas Preud'homme
Solved:
Last query:
Last reply:
Revision history for this message
Mallikarjun (mallikarjun-gouda) said :
#1

declaring InterruptVector with 'used' attribute kept the variable intact.

void (* const InterruptVector[])() __attribute__ ((used)) __attribute__ ((section(".vect_table"))) = {
0,
0,
0,
0
};

I wonder why does g++ remove it where as gcc does not when opt level >= O1

Revision history for this message
Best Thomas Preud'homme (thomas-preudhomme) said :
#2

Hi Mallikarjun,

As surprising as it is (it was to me), this is actually normal C++ behavior. C++11 contains the following gem in its 7.1.1 section:

"Objects declared const and not explicitely declared extern have internal linkage".

So all you have to do is prepend the "extern" keyword at the beginning of the line declaring (and in this case defining) InterruptVector.

Best regards.

Revision history for this message
Mallikarjun (mallikarjun-gouda) said :
#3

Thanks Thomas Preud'homme, that solved my question.