Compiler: MPLABX IDE V5.30
Operating system: Windows 10
What I’m trying to do is define some constant values (to make future changes easier) and create some other constants via arithmetic operations during preprocessing. Then use those constants during runtime.
Here is an example version of my intentions;
#include <stdio.h>
#include <math.h>
#define foo 100 // In case you change FOO in circuit, change this too!
#define bar (sqrt(foo))
int main(void) {
if ( bar > user_input)
{
do();
}
}
The problem is, I thought, since the input was a constant value, defined things would be calculated by the compiler and bar
would be replaced by 10
instead of (sqrt(foo))
. But when I compiled it, data and program size dramatically changed. When I disassembly it, there are tons of instructions instead of simply putting directly a number there.
Then I followed a suggestion from another question's answer and place a const squareroot()
function and const int
declaration, but the compiler gave an alert like;
main.c:50:38: error: initializer element is not a compile-time constant
Here is the second try;
#include <stdio.h>
#include <squareroot.h>
#define foo 100 // In case you change FOO in circuit, change this too!
const int bar = squareroot(foo);
int main(void) {
if ( bar > user_input)
{
do();
}
}
const int squareroot(const int input)
{
do()
}
How can I express myself to my compiler to make it understand some of the lines in my code are constant whatever happens during runtime, so that it can do the arithmetic instead of just simply passing the token/text to the function body?
#define
is a plaintext replacement and nothing more. All of the #define
transformations occur in the preprocessing translation phase which is before any analysis of expressions and so on.
The list of which expressions the compiler must support in a constant expression can be found in section 6.6 of the current C Standard, for a summary see here. Calling a function is not included.
(Of course, individual compilers may offer features not required by the Standard).
If you must use a compiler which does not support calling the floating point function sqrt
in a constant expression then your options include:
main
function .