ccompilationlinkercoderunner

C compiler can't find function definition


I'm new to C programming and encounter this question:

Three files: main.c, foo.h, foo.c are in the same directory.

main.c:

#include <stdio.h>
#include "foo.h"    
int main(){
    printf("%d",func(1));
}

foo.h declares function func:

int func(int);

foo.c defines function func:

#include "foo.h"
int func(int a){
    return a+1;
}

This code works as expected, but when I rename the definition file foo.c into something else, say bar.c, then main.c throw an error during compilation saying:

LLVM ERROR: Program used external function _func which could not be resolved!

I know that the definition file doesn't need to have the same name as the header file. Why the linker can't find the appropriate definition after I renamed foo.c into bar.c?

More generally, how does the linker search for function definition? Search every .c files in the same directory, one by one? Only search for definition in the .c file, which has the same file name as header file?

EDIT: I was using code-runner IDE on MacBook, don't know how the IDE actually compiles the source files.


Solution

  • Add the file name in the compilation command:

    $ gcc -o main main.c foo.c && ./main
                         ^^^^^