Itay Marom
Itay Marom

Reputation: 883

How to prohibit the use of global variables on compile time

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 ?

Upvotes: 22

Views: 1496

Answers (3)

Curd
Curd

Reputation: 12457

I would use ctags to extract the symbols from the source code and then search the output with a (perl or python) script for global variables.

E.g. following line would tell you whether a C soucre file hello.c contains global variables:

ctags -f- hello.c | perl -ne"@a=split(/\t/, $_); if ($a[3] eq qq(v)){ print qq(Has global variables.); exit 0; }"

Upvotes: 1

user23614
user23614

Reputation: 574

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.

Upvotes: 20

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

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.

Upvotes: 9

Related Questions