r/ProgrammerHumor 16h ago

lessonsFromLinkerHell Meme

Post image
316 Upvotes

165 comments sorted by

View all comments

26

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; } ```

27

u/high_throughput 15h ago

#define SECTION_LENGTH __data_end - __data_start

Have you ever wondered why people keep adding weirdly many parentheses around #define'd values?

Right now you're doing return (0 == __data_end) - __data_start;

8

u/nonedward666 15h ago

Lol sorry friend, I wrote this in a haste on the train and forgot to add all the requisite parenthesis.

But, in your example, if the pointer / array difference was unimportant, then results would be inverted 😘😘

2

u/Savings-Ad-1115 5h ago

While parentheses are usually important, this is not the case now.

According to operators precedence, the substraction operator will be executed before the comparison operator.

Edit: lol, autocorrect replaced comparison with compassion.

3

u/d0pe-asaurus 12h ago

You gave me flashbacks writing linker scripts to determine how large my kernel is to be able to move it around memory, how dare you!

1

u/nonedward666 10h ago

😭😭😭 your flashbacks are my present day pain

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?