ProcgerXacker
ProcgerXacker

Reputation: 123

How to call a function from another .c file

I wrote a program that in the main function calls a function from another .c file, but outputs an error undefined reference to 'function_name'. collect2: error: ld returned 1 exit status. I compile the program on the Linux command line: gcc -o main.exe main.c ./main.exe

funcs.h

#ifndef FUNCS_H_INCLUDED
#define FUNCS_H_INCLUDED

int foo();

#endif

second.c

#include <stdio.h>
#include "funcs.h"

int foo(){
  printf("Hello, world!");

return 0;
}

main.c

#include <stdio.h>
#include "funcs.h"

int foo();

int main(){
  foo();

  return 0;
}

how to fix the error

Upvotes: 2

Views: 1304

Answers (2)

Zig Razor
Zig Razor

Reputation: 3495

The undefined reference is raised when no symbol is detected for specific function.

In this case it can be fixed compiling also the .c file that contains the function so :

gcc -o main.exe main.c second.c

In this way you will have the symbol for the function you call that is in funcs.c file.

Upvotes: 0

Naomi
Naomi

Reputation: 5486

You need to compile all c files, not only main.c

gcc -o main.exe main.c second.c

Upvotes: 7

Related Questions