External variable at a specific address

Using C ++ and GCC, can I declare an external variable that uses a specific address in memory? Sort of

int key __attribute__((__at(0x9000)));

AFAIK this particular parameter only works with embedded systems. If there is such an option for use on the x86 platform, how can I use it?

+3
source share
7 answers

Simple option:

Identify

int * const key = (int *)0x9000;

and *keylink to elsewhere (or use the link).

Non-error option:

externs ! , . extern int key;, key . script (. ld) , --defsym.

gcc, -Xlinker, .

gcc -o outfile -Xlinker --defsym -Xlinker key=0x9000 sourcefile.c

, , 0x9000.

#include <stdio.h>
extern int key;
int main(void) {
    printf("%p\n", &key);
    return 0;
}

, - , , , , ld script.

+10

GCC. , . , , , , ,

int init_data __attribute__ ((section ("INITDATA")));

, [] , :

int* pkey = ( int* )0x9000;
*pkey = 0xdeadbeef;
+4

:

#define KEY (*(int*)0x9000)

KEY , KEY .

(, - - ), volatile:

#define KEY (*(volatile int *)0x9000)

, , , , , .

+3

++, . :

// an object type T at address 0x9000
T* t = new(reinterpret_cast<void*>(0x9000)) T;

, , new . , , .

+1

( - , ), MMU x86. , , - .

/ - ? x86 ... dlsym() - Linux, GetProcAddr() Windows. AFAIK.

lib dll , . ( , )

0

, IAR C ,

char foo @ 0x9000;

, , MSP430. GCC MSP430, , , , , IAR.

-, , , .

#define CONST_ADDR_VAR( type, name, address ) type *const name##_addr =(type *)address

, ,   #define var (* var_addr)

, , . , GCC.

, , , , , extern C.

GCC __attribute__((section( ... ) )) , , . , , , , .

http://www.ohse.de/uwe/articles/gcc-attributes.html#var-section

0

No. Modern desktop operating systems use virtual memory, which means that any address that you have is meaningless until you give it to the OS, making the specific memory address useless. On the desktop / x86 there is no advantage and no advantages.

-2
source

Source: https://habr.com/ru/post/1749765/


All Articles