Search code examples
cgccincludeclangcross-compiling

undefined reference to `printf' in cross-compilation using clang


I execute below code to create .o file

   clang --target=i686-pc-none-elf -march=i386 -c fcfs.c -o fcfs.o -std=gnu90 -O2 -Wall -Wextra -Wall

and then while I execute below code

i686-elf-ld -T linker.ld -o JOS.bin fcfs.o

I got error says

**fcfs.c:(.text+0x13): undefined reference to `fopen'
fcfs.c:(.text+0x45): undefined reference to `fgets'
fcfs.c:(.text+0x57): undefined reference to `printf'**

my fcfs.c file

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(){
    char dataToBeRead[50];
    int a = abs(-5);
    FILE *fp;
    fp = fopen("process.txt", "r");
    // int fp=1;
    printf("%d", a);
    int s;
    if(fp != NULL){
        printf("File is not empty");

          while( fgets ( dataToBeRead, 50, fp ) != NULL ) 
        { 
          
            // Print the dataToBeRead  
            printf( "%s" , dataToBeRead ) ; 
         } 
    }
    return 0;
}

Why I am getting this error. Do I need to add some more arguments to clang related to library linking? Can I use gcc libraries in clang? Or it is problem of i686-elf-ld ?


Solution

  • Clang do support header files like stdio.h , stdlib.h and other header files.

    If you are facing issue like

    fcfs.c:(.text+0x13): undefined reference to `fopen'
    fcfs.c:(.text+0x57): undefined reference to `printf'
    

    in clang you can solve it by adding --sysroot to your clang options. In my case

       clang --target=i686-pc-none-elf -march=i386 --sysroot=/usr -c fcfs.c -o fcfs.o -std=gnu90 -O2 -Wall -Wextra -Wall
    

    In this case -sysroot will start looking for header files from /usr folder. In /usr it will find folders like /bin ,/include ,etc. and when it goes to /include folder it will find all header files and that will solve problem.

    for more info refer https://clang.llvm.org/docs/CrossCompilation.html