How do I use clang to compile for avr (arduino)

Viewed 2688

When I search I found 7yr old results talking about a fork of clang instead of clang itself.

Using avr-gcc I can compile and upload my code with

avr-gcc a.cpp -DF_CPU=16000000 -mmcu=atmega2560 -Wall -Werror -Wextra -Os
avr-objcopy -j .text -j .data -O ihex a.out my.hex
sudo avrdude -patmega2560 -cwiring -P/dev/ttyACM0 -b115200 -D -Uflash:w:my.hex:i

I'd like to replace the first step with clang++. The changes I made here

  • avr-gcc to clang++
  • Added --target=avr
  • Added -nostdlib because I'll include it myself
  • Added -I/usr/avr/include/ because path wasn't implicit
  • Added -L/usr/avr/lib/avr6 -lc -latmega2560 so it has enough info to build an elf

I found device-specs at /usr/lib/gcc/avr/10.2.0/device-specs/specs-atmega2560 which mentions crtatmega2560.o and -latmega2560 which appears to be located at /usr/avr/lib/avr6/. So I came up with the following and got these errors. How should I be compiling so I can get a hex to upload using avrdude?

$ clang++ a.cpp -DF_CPU=16000000 -mmcu=atmega2560 -Wall -Werror -Wextra -Os --target=avr -I/usr/avr/include/ -nostdlib -L/usr/avr/lib/avr6 -lc -latmega2560
/usr/bin/avr-ld: skipping incompatible /usr/avr/lib/avr6/libc.a when searching for -lc
/usr/bin/avr-ld: cannot find -lc
/usr/bin/avr-ld: skipping incompatible /usr/avr/lib/avr6/libatmega2560.a when searching for -latmega2560
/usr/bin/avr-ld: cannot find -latmega2560
2 Answers

AVR target is experimental in LLVM compiler for which clang is the C and C++ front-end. To enable experimental targets you must compile LLVM from source. This Stack Overflow answer describes how to do it.

Looking at the bug tracker I see there are good reasons why it is experimental.

I am not sure what to answer finally.

Probably it is not the worst idea to compile .o file with clang, and link everything manually just like you wish.

I am not sure, if it is needed to enable any experiment features, due I tried to compile something to AVR, and it works fine with clang-12 when I use llvm repository apt.llvm.org.

Related