7

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 :)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
nigong
  • 1,727
  • 3
  • 19
  • 33
  • 2
    Can you provide some code example for more clarity? – Caesar Oct 17 '13 at 22:45
  • I think doing what you are trying to do goes against the philosophy of the C language. Could you explain a little more ? – Rerito Oct 17 '13 at 22:47
  • 1
    What are you planning to use the label for if not as the target of a `goto`? That's really all it's designed for in C and C++, so labels aren't visible outside the function in which they're defined. – Jerry Coffin Oct 17 '13 at 22:57
  • 2
    What's the point of the "label"? – Kerrek SB Oct 17 '13 at 22:59

2 Answers2

5

According to the C++ Standard

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
5

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?

trozen
  • 1,117
  • 13
  • 13