Dunfield Development Services Inc.
Customer Support -- Application Note #0011
MICRO-C
Common #defines for C and assembly language

Applies to: [Micro-C Compiler
]
Last updated: Sunday May 04, 2003
.
Application Note Index
[ Back ] [ Next ]

PROCEDURE
It is often desirable to be able to use a single set of defined constants, and to have them
accessible from both C and assembly language.
With Micro-C, this is fairly easy, especially if you are using inline assembly language. To use C #defined constants within inline assembly
language, all you have to do is make sure that you are using the MCP extended pre-processor (-P option to CCxx or "Preprocess" option within
DDSIDE). When MCP is used, all input to the compiler (including the inline assembly code) will be handled by the pre-processor.
Note that while C and the assembler agree on the format of decimal numbers, they disagree on the format of hexidecimal constants. C wants
the form '0x##' and most assemblers will expect '0##H' or '$##' (Where '##' is the hex constant value). The easiest solution to this problem
is to use only DECIMAL constants, however you can use hex values with a little pre-processor trick where you prepend '0x' in C blocks, and
prepend '$' in assembly blocks (See the example code below).
If you are not using inline assembly, you can still accomplish this by running your assembly code through a C pre-processor prior to
assembling it. This will allow the use of #define constants, as well as conditionals
(#if/#ifdef/#ifndef) and #include files. It can be
very useful to put your common #defines into a single .h file, and then #include it from both the C and the assembly language files.
The following is a small example in C and 8051 assembly language which demonstrates the use of common #define constants (both decimal and hex):
----------------------- Cut here ---------------------
#include <8051io.h>
#define CONST_DEC 1234 /* A decimal constant */
#define CONST_HEX ABCD /* A hex constant */
/* Load a constant in decimal from assembly language */
/* Decimal constants are the same in C or assembly */
get_example1() asm
{
MOV A,#CONST_DEC ; Load low accumulator
MOV B,#=CONST_DEC ; Load high accumulator
}
/* Load a constant in hex from assembly language */
/* Note the '$', NULL COMMENT prefix: ($/**/) */
/* to get the HEX constant within assembly language */
get_example2() asm
{
MOV A,#$/**/CONST_HEX ; Load low accumulator
MOV B,#=$/**/CONST_HEX ; Load high accumulator
}
main()
{
/* Decimal constants are the same in C or assembly */
printf("Example1 (C) = %u\n", CONST_DEC);
printf("Example1 (ASM) = %u\n", get_example1());
/* Note the '0x', NULL COMMENT prefix: (0x/**/) */
/* to get the hex constant within C */
printf("Example2 (C) = %x\n", 0x/**/CONST_HEX);
printf("Example2 (ASM) = %x\n", get_example2());
}
--------------- This is the output --------------
Example1 (C) = 1234
Example1 (ASM) = 1234
Example2 (C) = ABCD
Example2 (ASM) = ABCD |
|