abimarper
abimarper

Reputation: 11

Declare variables in the same address of other variables in XC8

I have the following problem with XC8 compiler I had an array --> char my_array[8];
but for convenience, I want to declare the variable --> unsigned int cont_up; at the same address of my_array[5] on CC5x compiler its very easy to do. You only have do the following:

char my_array[10]; 
unsigned cont_up:16 @my_array[5];

I don't know how to do it with the XC8 compiler

Upvotes: 1

Views: 40

Answers (2)

Lundin
Lundin

Reputation: 214495

All embedded systems use the stdint.h types and stick to unsigned types in the vast majority of cases. This is because the default types in C are non-portable and we do not want signed arithmetic when working close to hardware, since that comes with a lot of poorly-defined behavior bugs. The char type is particularly problematic since it has compiler-specific signedness. So step #1 is to port your code over to the reliable industry standard stdint.h.


The way to access the same data with different types in C, safely and portably without non-standard extensions, is to use union. In your case, for example:

#include<stdint.h>

typedef union
{
  uint8_t  u8  [8];
  uint16_t u16 [4];

  struct 
  {
    uint16_t here_are;
    uint16_t weird;
    uint8_t  names;
    uint16_t cont_up;
    uint8_t  the_end;
  };
} array_t;

The u8 member allows byte-by-byte access, the u16 word-by-word access, and the anonymous struct (ISO C11 feature) covers any other strange naming urges.

So now you can do array_t array; ... array.u8[5] or array.cont_up and that points at the same place in memory.

Notably cont_up is purposely misaligned here as requested - won't be a problem on an old 8-bit MCU but it probably will be on many 16 or 32 bitters. It's best practice not to come up with such strange data layouts even on 8 bit systems.

Also note that your 8-bitter ABI (likely decided by the compiler) will have an endianness even though the CPU doesn't. Often the same endianness as the address bus. PIC is out of tradition little endian. So array.cont_up = 0xAABB; ... array.u8[5] will result in 0xBB and that hopefully won't come as a surprise to any PIC programmer.

Upvotes: 0

Khai
Khai

Reputation: 9

so yk, In the XC8 compiler, you can't directly use the @ syntax like you can do in CC5X to assign a variable to a specific memory address.

here's an example,

#include <xc.h>

char my_array[10];
unsigned int *cont_up; 

void main() {
    cont_up = (unsigned int *)&my_array[5]; 

    
    *cont_up = 0xABCD; 

   
    while (1);
}

Upvotes: 0

Related Questions