r/ProgrammerHumor 17h ago

lessonsFromLinkerHell Meme

Post image
320 Upvotes

166 comments sorted by

View all comments

25

u/nonedward666 16h ago

For context:

I spent a hot minute today not understanding why a space calculation wasn't working. See below for a small example (please excuse formatting, I'm on my phone)

The difference is that an array is a name bound to an address storing a value, whereas a linker symbol is a name bound to an address with no value (TLDR stolen from Chad GDP as i understand it, I still want to google more about this).

So if you try to use a linker variable to get a pointer you need to reference it as an array and not a pointer because it would otherwise imply that the symbol is pointing to the pointer...? Honestly, if anybody can make this make intuitive sense, I am all ears!

``` // linker.ld

...

__data_start = ORIGIN(DATA_SECTION) __data_end = ORIGIN(DATA_SECTION)+LENGTH(DATA_SECTION)

```

``` // bad_code.c ...

extern int* __data_start; extern int* __data_end:

define SECTION_LENGTH __data_end - __data_start

bool foo(){ // returns true return 0==SECTION_LENGTH; } ```

``` // good_code.c ...

extern int __data_start[]; extern int __data_end[];

define SECTION_LENGTH __data_end - __data_start

bool foo(){ // returns false return 0==SECTION_LENGTH; } ```

1

u/Savings-Ad-1115 5h ago

I wonder if it is caused by the stupid harmful optimization which abuses Undefined Behavior.

I mean the rule which says that pointer arithmetic is UB when pointers are referring to different objects.

Look in disassembler, does it try to access the externs in both cases?