Search code examples
c++cubuntuclangriscv

Clang compiler couldn't find C/C++ standard libraries when I gave a specific target although it works without giving target


I am currently using clang11 on ubuntu to compile any c/c++ code and it works fine but when I tried to compile any code (including any standard library) to assembly code for any specific target like x86_64 (even I have x86_64) riscv with giving a flag that --target=x86_64 or --target=riscv32 I got errors for any standard library that I included in my code. A simple example:

// ex.cpp
#include<iostream>
int main(){
    int a = 5;
    int b = 3;
    std::cout << a - b;
}

Without giving flag for a spesific target works fine:

clang++-11 -S ex.cpp -o ex.s

With --target=riscv32 flag:

clang++-11 --target=riscv32 -S ex.cpp -o ex.s

gives this error: ex.cpp:1:9: fatal error: 'iostream' file not found

also without standard libraries gives no error even I give a spesific target.

I am searching for a solution for days but I couldn't find any proper solution for this problem, most of them says try to include gnu libraries and subfolders like -I/usr/include/x86_64-linux-gnu/c++/ but it doesn't work for me.

Please don't say use g++ compiler, for adding an optimization I need clang.

Actually I am trying to compile my codes for riscv target, linking with g++ and running with spike (doesn't differ --target=... or -target ...):

clang++-11 -target riscv32-unknown-elf -march=rv32gc -fno-addrsig -S ex.cpp -o ex.s
~/riscv/bin/riscv32-unknown-elf-g++ ex.s -o ex
~/riscv/riscv-isa-sim/build/spike --isa=RV32GC ~/riscv/riscv-pk/build/pk ex

And it works fine without include a standard library. Now, I want to ask that

Can I solve this problem simply?

or

Can I use clang directly from riscv bin utils like ~/riscv/bin/riscv32-unknown-elf-clang++ (I saw something like this on the net but couldn't find) adding and building a submodule to my riscv directory?

Edit: As @NateEldredge said, for x86_64 target triple should --target=x86_64-linux-gnu but for riscv as a target triple riscv32-unknown-elf I still have the same errors. Is there a proper target flag for riscv any other than --target=riscv32-unknown-elf? Maybe I am missing that point.


Solution

  • I solved my problem by linking compilations with riscv-gnu-toolchain built and also answered a similar question here in detailed: Using Clang to compile for RISC-V

    Simply we need cross-compilation. Further information you can also look here: https://github.com/lowRISC/riscv-llvm#how-can-i-build-upstream-llvmclang-and-use-it-to-cross-compile-for-a-riscv32-target