Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prohibit the use of global variables on compile time

Tags:

Is there a way to prohibit the use of global variables?

I want GCC to generate an error on compile time when a global variable is defined.

We have a code that should be run per thread and want to allow only use of stack (which is thread safe)

Is there way to enforce it ?

Some GCC flag or other way to verify it ?

like image 447
Itay Marom Avatar asked Jul 08 '14 13:07

Itay Marom


2 Answers

One approach would be to generate a linker map file (e.g. pass option -Wl,-Map,program.map to gcc), and examine the .data and .bss output sections for any contributions from the object files that you want to run without globals.

For instance, if my source file hello.c has:

static int gTable[100]; 

the linker map file will have something like this in it:

.bss            0x0000000000600940      0x1b0  *(.dynbss)  .dynbss        0x0000000000000000        0x0 /usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o  *(.bss .bss.* .gnu.linkonce.b.*)  .bss           0x0000000000600940        0x0 /usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crt1.o  .bss           0x0000000000600940        0x0 /usr/lib/gcc/x86_64-linux-gnu/4.7/../../../x86_64-linux-gnu/crti.o  .bss           0x0000000000600940        0x1 /usr/lib/gcc/x86_64-linux-gnu/4.7/crtbegin.o  *fill*         0x0000000000600941       0x1f 00  .bss           0x0000000000600960      0x190 hello.o 

You can see that hello.o is contributing 0x190 (400) bytes to the .bss section. I've used the approach of parsing a link map file with a Python script to generate code size and RAM usage metrics for an embedded project with reasonable success in the past; the text output format from the linker is pretty stable.

like image 133
user23614 Avatar answered Sep 20 '22 17:09

user23614


No such functionality in gcc. Some workaround would be to incorporate in the build process a static analysis tool which can detect globals. Still the compilation would not fail, but at least you would be warned in some way. I can see that PC-Lint (www.gimpel.com) has a check for

non const non volatile global variables, locating these can assist multi-threaded applications in detecting non re-entrant situations

Probably other tools may include similar functionality.

like image 33
Wojtek Surowka Avatar answered Sep 18 '22 17:09

Wojtek Surowka