undefined reference to `printf'

21,168

Unless you have your own version of printf somewhere, you'll have to link with the C runtime library.

Pass the option -lc to the ld command.

Share:
21,168
Searene
Author by

Searene

A social nerd.

Updated on May 15, 2020

Comments

  • Searene
    Searene almost 4 years

    test.c and kernel.asm are in the folder src, Makefile is in the folder Debug, just like that:

    src
        test.c
        kernel.asm
    Debug
        Makefile
    

    All these files are very simple codes. But if I run make in the folder Debug,I will get the following error:

    ld -Ttext 0x30400 -o test ../Debug/kernel.o ../Debug/test.o
    ../Debug/test.o: In function `Print_String':
    test.c:(.text+0xf): undefined reference to `printf'
    

    Can someone tell me why? Contents are as follows:

    test.c

    #include <stdio.h>
    
    int m = 1;
    void Print_String()
    {
        printf("TEST");
    }
    

    kernel.asm

    extern m
    extern Print_String
    
    [section .text]
    global _start
    _start:
        mov eax, m
        call Print_String
    

    Makefile

    # This Program
    TARGET  = test
    
    # All Phony Targets
    .PHONY : everything clean all
    
    DIR     = ..
    
    OBJ     = $(DIR)/Debug/kernel.o $(DIR)/Debug/test.o
    C_FILE  = $(DIR)/src/test.c
    K_ASM   = $(DIR)/src/kernel.asm
    
    ASM     = nasm
    LD      = ld
    CC      = gcc
    
    CC_FLAG  = -c -g
    ASM_FLAG = -f elf
    LD_FLAG  = -Ttext 0x30400
    
    # Default starting position
    everything : $(TARGET)
    
    clean :
        rm -f $(TARGET)
    
    all : clean everything
    
    kernel.o : $(K_ASM)
        $(ASM) $(ASM_FLAG) -o $@ $<
    
    test     : $(OBJ)
        $(LD) $(LD_FLAG) -o $@ $(OBJ)
    
    test.o   : $(C_FILE)
        $(CC) $(CC_FLAG) -o $@ $<
    
  • Junior Mayhé
    Junior Mayhé about 4 years
    for those trying to find how to use -Lc argument to specify the folders, here is a sample stackoverflow.com/questions/44361841/…