Why cant register variables be made global?

后端 未结 9 1416
时光说笑
时光说笑 2021-02-06 13:33

While reading from a site a read that you can not make a global variable of type register.Why is it so? source: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.js

相关标签:
9条回答
  • 2021-02-06 14:07

    Actually, GCC allows this. A declaration in global scope in the form:

    register int foo asm ("r12");
    

    Allocates the register "r12" (on x86_64) for the global "foo". This has a number of limitations and the corresponding manual page is probably the best reference to all the hassle global register variables would make:

    • http://gcc.gnu.org/onlinedocs/gcc/Explicit-Reg-Vars.html
    0 讨论(0)
  • 2021-02-06 14:10

    Because it would be senseless. Global variables exist all the time the application is working. There surely is no free processor register for such a long time ;)

    0 讨论(0)
  • 2021-02-06 14:11

    The register word is used in C/C++ as request to the compiler to use registers of processor like variables. A register is a sort of variable used by CPU, very very fast in access because it isn't located in memory (RAM). The use of a register is limited by the architecture and the size of the register itself (this mean that some could be just like memory pointers, other to load special debug values and so on).

    The calling conventions used by C/C++ doesn't use general registers (EAX, EBX and so on in 80x86 Arch) to save parameters (But the returned value is stored in EAX), so you could declare a var like register making code faster.

    If you ask to make it global you ask to reserve the register for all the code and all your source. This is impossible, so compiler give you an error, or simply make it a usual var stored in memory.

    0 讨论(0)
  • 2021-02-06 14:13

    Because they're in registers. It's a contradiction in terms.

    0 讨论(0)
  • 2021-02-06 14:16

    Originally, register variables were meant to be stored in processor registers, but global variables have to be stored in the data or the BSS section to be accessible from every function. Today, compilers don't interpret the register storage class strictly, so it remains largely for compatibility reasons.

    0 讨论(0)
  • 2021-02-06 14:27

    So do we all agree now? Do we all see that making a global variable a register variable would be a really, really bad idea? If the original C definition did not forbid it, it was probably because nobody thought anyone would actually implement it that way -- as they should not have especially back in CISC days.

    Besides: modern optimizing compilers do a better job of deciding when to keep variables in registers than humans can do. If yours can't do it, then you really, REALLY need to get a better compiler.

    0 讨论(0)
提交回复
热议问题