undefined reference error

i have just started with c programming.And when i try to compile the following code i get an error:

In function 'main':
main.c:8:undefined reference to 'func'
collect2:error: ld returned 1 exit status

but when i put the function to the header file and delete the extra.c file it runs fine.




main.c
1
2
3
4
5
6
7
8
 #include <stdio.h>
 #include "header.h"

  int main() 
   {
       printf("%d \n",func());
       return 0;
    }



header.h
1
2
3
4
5
6
#ifndef HEADER_H
#define HEADER_H

extern int func();

#endif 


extra.c
1
2
3
4
5
6
#include "header.h"

int func()
{
  return 2015;
}
Last edited on
Did you add extra.c to your project or compile line? You have a linker error telling you the linker could not find the function implementation.

By the way your header should have include guards and there is probably no need for the extern qualifier for the function. You also don't need to #include the <stdio.h> include file in the header or extra.c.
Last edited on
i added extra.c only to the project.

by the way thanks for telling about the guards i didnt knew them as i said i am new.
i found the the mistake. it was very silly actually. i thought extra.c will automatically get compiled like a normal .h header file but i also had to compile extra.c and now it works. thankyou jlb
Topic archived. No new replies allowed.