Hi, I am trying to compile a example code from Atmel, which was written for Atmel Studio IDE, GCC or IAR compilers, and getting the following error:
error: #59: function call is not allowed in a constant expression
This is an similar example of the code:
const sam_abc xy_settings = {function_yz(), 111, 250 };
- sam_abc is a struct - function_yz() is the function which causes the error
I am using µVision V4.54.0.0 (C Compiler: Armcc).
How could I solve this problem? Can someone please help me. Thanks in advance.
Jan
Only, "similar" ?
So what was the actual code that Atmel provided? Does that compile?
"How could I solve this problem?"
The error message tells you exactly:
function call is not allowed in a constant expression
So don't do that, then!
I just changed the name of the struct and the name of function in my first post, because I thought it would be easier for other people with the same error.
I didn't change anything in Keil. I just copied the code from Atmel and it doesn't compile.
The function just returns the frequency of the CPU clock and I was just wondering if it's possible to use this value in the const. expression.
A const value has to be determined at compile time (and likely gets stored in flash). This isn't possible if the value comes from a function.
Thanks for the help!
So this looks like to be a compiler specific error (?), because the code compiles without any errors using Atmel Studio.
I thought there could be a solution to use the value of the function in the const expression anyhow. But now I will insert the value directly.
If the const variable is automatic, it will be allocated on the stack (or in registers) and initialized at function entry every time the function is called. From reading of the language standard, this code is legit as long as the declaration is located within a function. Also, some functions return a constant value that can be calculated at compile time, and some compilers do take advantage of that. But that's not really an issue since the language standard does not allow this in constant expressions.