millfork icon indicating copy to clipboard operation
millfork copied to clipboard

Non-constant literal initialization is not supported

Open agg23 opened this issue 3 years ago • 3 comments

The compiler allows you to initialize a global variable with a literal: const byte test = 1, but doesn't actually generate any code to initialize those variables on program start.

word input = 1000
byte output

void main() {
  func(input)

  if (output == 0) {
    asm {
      kil
    }
  }

  while (true) {}
}

void func(word func_input) {
  output = func_input.hi
}

void nmi() {
  
}

void irq() {

}

Built with java -jar millfork.jar main.mfk -o build/rom.nes -t nes_small -g -s -fsource-in-asm -fillegals

agg23 avatar Jan 02 '21 17:01 agg23

I guess the compiler should warn about it, but initialization of variables on ROM-based targets requires manual handling right now: https://karols.github.io/millfork/api/rom-vs-ram.html

In your case, it should just be enough to call init_rw_memory() near the beginning of the program.

KarolS avatar Jan 06 '21 00:01 KarolS

Interesting. Good to know that exists. What is the rationale behind not running it immediately on start?

agg23 avatar Jan 06 '21 00:01 agg23

It lets you defer it for later if you want to do some hardware initialization beforehand, and also it is in line with Millfork's "middle-level language" philosophy. It also has bonus points of being able to reset your program's memory with a single line of code (as you can call init_rw_memory() whenever you want as many times you want).

Currently, Millfork is not designed to have any kind of runtime, it just goes straight to your main function in the simplest and fastest way necessary. In comparison, C runtime does many things like memory initialization before it finally calls main.

KarolS avatar Jan 06 '21 01:01 KarolS