Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access 32-bit registers in C?

Is it possible to access 32-bit registers in C ? If it is, how ? And if not, then is there any way to embed Assembly code in C ? I`m using the MinGW compiler, by the way. Thanks in advance!

like image 726
C4theWin Avatar asked Jun 11 '10 10:06

C4theWin


People also ask

Can you access registers in C?

To access a specific register, the code first needs to write the register number to the device and then perform the required write/read operation. This is not difficult, but needs to be managed carefully.

How many registers are there in C?

5) There is no limit on number of register variables in a C program, but the point is compiler may put some variables in register and some not.

What is register in embedded system?

Registers are used in the CPU to store information on temporarily basis which could be data to be processed, or an address pointing to the data which is to be fetched. In 8051, there is one data type is of 8-bits, from the MSB (most significant bit) D7 to the LSB (least significant bit) D0.


2 Answers

If you want to only read the register, you can simply:

register int ecx asm("ecx");

Obviously it's tied to instantiation.

Another way is using inline assembly. For example:

asm("movl %%ecx, %0;" : "=r" (value) : );

This stores the ecx value into the variable value. I've already posted a similar answer here.

like image 134
jweyrich Avatar answered Oct 23 '22 11:10

jweyrich


Which registers do you want to access?

General purpose registers normally can not be accessed from C. You can declare register variables in a function, but that does not specify which specific registers are used. Further, most compilers ignore the register keyword and optimize the register usage automatically.

In embedded systems, it is often necessary to access peripheral registers (such as timers, DMA controllers, I/O pins). Such registers are usually memory-mapped, so they can be accessed from C...

by defining a pointer:

volatile unsigned int *control_register_ptr = (unsigned int*) 0x00000178;

or by using pre-processor:

#define control_register (*(unsigned int*) 0x00000178)

Or, you can use Assembly routine.

For using Assembly language, there are (at least) three possibilities:

  1. A separate .asm source file that is linked with the program. The assembly routines are called from C like normal functions. This is probably the most common method and it has the advantage that hw-dependent functions are separated from the application code.
  2. In-line assembly
  3. Intrinsic functions that execute individual assembly language instructions. This has the advantage that the assembly language instruction can directly access any C variables.
like image 36
PauliL Avatar answered Oct 23 '22 11:10

PauliL