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
In my case, I added "GNU extensions" ticked in Target Build Options - C/C++ , removed this error.
Here's my new settings screenshot..
Just by disabling this GNU extensions, the error re-appears.
Yes, I very much suspect that is the case.
It might be a GCC extension - or it might be a mistake by the OP when he "just (sic?) changed the name"...
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.
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.
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.
Does the sam_abc structure contain a function pointer member? If so then I would suggest that function_yz() should actually be function_yz (or &function_yx) so that the structure contains the addresses of the function rather than attempting to call it.
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.
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!
View all questions in Keil forum