Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a global label in C/C++

Tags:

c++

c

scope

label

I just simply wanted to define a global label pointing to one line of code in a.c file and then the b.c file can recognize that label. Both the files are linked together. The problem is the b.c file couldn't recognize it since the compiler/linker thinks the label in a.c file is file specific.

I found a similar question and answer here: Use label in Assembly from C But I wanted to define a global label in C/C++ rather than in Assembly.

P.S., I am not using goto statement :)

like image 271
nigong Avatar asked Oct 17 '13 22:10

nigong


2 Answers

According to the C++ Standard

The scope of a label is the function in which it appears.

like image 154
Vlad from Moscow Avatar answered Sep 25 '22 15:09

Vlad from Moscow


In GCC you can do it with inline assembly:

#define LABEL_SYMBOL(name) asm volatile("labelsym_" name "_%=: .global labelsym_" name "_%=":);

and then in your code:

LABEL_SYMBOL("xxx")

The _% appended to the symbol makes sure it's unique in compilation unit (https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Special-format-strings).

Then you can find all symbols inspecting ELF program header, as described in: List all the functions/symbols on the fly in C code on a Linux architecture?

like image 28
trozen Avatar answered Sep 26 '22 15:09

trozen