简体   繁体   中英

C++ - global pointer to function

why this works? I think global data are "initialized" at compile time (compiler saves to .global section in obj file format null bytes, so when the section is loaded into memory, it is initialized to null). So how can be initialized pointer to function address, if compiler doesn't know where the function will be in memory at runtime?

#include <iostream>

void vypis();

int neco;
int * bla = &neco;
void (*vypis_ptr)() = vypis;

int main(int argc, const char * argv[])
{

}

void vypis() {

}

I removed the redundant include of iostream so that your source actually compiles as C and compiled it on my system to an executable called vypis. Here is what I found:

$ nm vypis | fgrep vypis
00000000004004d0 T vypis
0000000000600888 D vypis_ptr

So, vypis , a function, is a global in the "text" section and vypis_ptr , a pointer to a function, is a global in the "data" section.

Objects in the data section have values stored in the executable and I can read what's in vypis_ptr by dumping out the data section with objdump .

$ objdump -d -j .data vypis

vypis:     file format elf64-x86-64


Disassembly of section .data:

0000000000600878 <__data_start>:
        ...

0000000000600880 <__dso_handle>:
        ...

0000000000600888 <vypis_ptr>:
  600888:       d0 04 40 00 00 00 00 00                             ..@.....

0000000000600890 <bla>:
  600890:       a8 08 60 00 00 00 00 00                             ..`.....

Here we can see that the value 4004d0 is stored in vypis_ptr but this is exactly the location of vypis as displayed in the output of nm .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM