2
#include<stdio.h>
int main()
{
     int x = 5;
     int length = 5+x;
     int arrayw[length];


        return 0;
}

This code builds fine in gcc and Keil but not in IAR.

I get this error : 
Error[Pe028]: expression must have a constant value 

How can it be made to compile fine in IAR toolchain

Raulp
  • 7,758
  • 20
  • 93
  • 155
  • 1
    [Variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) were introduced in the C99 standard. Compiler for embedded systems often lag behind the current standards. It seems like the IAR compiler lags behind quite a bit. – Some programmer dude Sep 26 '19 at 12:23
  • 2
    @Someprogrammerdude As far as I remember VLA:s are, as of C11, no longer required by a conforming compiler. – Johan Sep 26 '19 at 12:25
  • 2
    @Johan Only if it does`#define __STDC_NO_VLA__ 1`. No VLA support would make the compiler dysfunctional though. Although allocating instances of VLA is mildly useful - particularly for embedded - using _pointers_ to VLA is a fundamental part of modern C programming. – Lundin Sep 26 '19 at 12:40
  • What happens when you write `int arrayw [__STDC_NO_VLA__];` instead? – Lundin Sep 26 '19 at 12:45
  • @Lundin iccarm set `__STDC_NO_VLA__` to 1 unless --vla is given. – Johan Sep 26 '19 at 12:46
  • @Johan There's no telling which version of the compilers the OP got so this would be the first step. – Lundin Sep 26 '19 at 12:47

2 Answers2

3

Follow this: https://netstorage.iar.com/SuppDB/Public/UPDINFO/013556/ew/doc/infocenter/GettingStarted/CreatingAnApplicationProject/CreatingAnApplProj.ENU.html

On the step where it says Setting project options make sure to select C99.

Here is the window you're looking for:

enter image description here

P.S. There is also an option to explicitly allow VLA in IAR. See http://www.keil.com/support/man/docs/armcc/armcc_chr1359124950297.htm

John
  • 1,012
  • 14
  • 22
  • Which IAR is this? I have C89 option and then Standard C option in IAR 8.40.1 (is it the same as C99) , but it works if I tick Allow VLA under it. – Raulp Sep 26 '19 at 18:20
  • @Raulp IAR Embedded Workbench for Microchip AVR version 7.20.1 – John Sep 26 '19 at 18:52
  • 1
    @Raulp Also checkout page 220 at http://ftp.iar.se/WWWfiles/arm/webic/doc/EWARM_IDEGuide.ENU.pdf which covers your IAR version. – John Sep 26 '19 at 18:55
3

Variable length arrays must be explicitly enabled for the compiler to recognize them. This can be done by adding --vla to the compiler command line or by checking C/C++ Compiler > Language 1 > Allow VLA in the options dialog in IDE.

Note that the VLA generated by iccarm are allocated on the heap.

Johan
  • 3,667
  • 6
  • 20
  • 25