1

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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
o_yeah
  • 688
  • 7
  • 17
  • 5
    How did you compile? you have to pass the object file to the linker `-o ...` – Tony Tannous Aug 03 '20 at 08:38
  • 1
    @o_yeah Please edit your question including your compilation line. Have you tried including the two C files in your compilation line? Something like `gcc main.c bar.c`? – rturrado Aug 03 '20 at 08:44
  • 1
    The linker searches for function definitions in the files you told him to link. So probaly the way you compile/link is wrong. You need to show us how you compile/link. If you ise an IDE, you need to tell us which one you use. Also tell us what platform you're on. – Jabberwocky Aug 03 '20 at 08:55
  • Are you using this: https://coderunnerapp.com/ ? – Jabberwocky Aug 03 '20 at 12:39
  • @Jabberwocky yes – o_yeah Aug 03 '20 at 15:59

1 Answers1

2

Add the file name in the compilation command:

$ gcc -o main main.c foo.c && ./main
                     ^^^^^
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34