Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how to call functions from another source file in C

Tags:

c

codeblocks

I am trying to properly understand how to call C functions from another source file in C. I have a simple example that I am trying to get working. I have two functions, function1 and function2, which are contained in file.c. I am attempting to call function 2 from main.c bur receive the error "undefined reference to function 2".

main.c

#include <stdio.h>
#include <stdlib.h>
#include "file.h"
int main()
{
    int result = function2(3);
    printf("Result = %d  ", result);
    return 0;
}

file.c

int function1(int a)    /* Function 1  definition */
{
    int val = a*a;

    return val;
}

int function2(int val)    /* Function 2 definition */
{
    return val +5;
}

file.h

#ifndef FILE_H_INCLUDED
#define FILE_H_INCLUDED
extern int function1(int a) ;
extern int function2(int val);


#endif // FILE_H_INCLUDED

(I know that function1 and function2 can be combined into one function but I want to understand why this example isn't working! - thanks)

like image 988
Sjoseph Avatar asked Sep 17 '25 04:09

Sjoseph


2 Answers

  • In Codeblocks, File -> New -> Project.
  • Pick console application. Next.
  • Pick language C. Next.
  • Pick a project title path etc. Next.
  • Compiler should be GCC, don't touch any settings. Finished.
  • In the project window, add the relevant files to the project. You already get a main.c, so create a file.c and add it. It is convenient to add the h file too, although not necessary.
  • Build & run.
  • Output: Result = 8

Works fine with copy/paste of your code into main.c file.c file.h


Misc good advice not related to the problem:

  • Settings -> Compiler -> Compiler flags tab. Check the options corresponding to -Wall -Wextra and -pedantic-errors. If there is no C11 option, add one. See this.

  • As someone pointed out, you should always #include "file.h" from file.c

like image 124
Lundin Avatar answered Sep 18 '25 21:09

Lundin


Your source code is correct. What you are probably not doing is linking the two object files together to create an executable.

From the command line, compile both files into object files

cc -Wall -std=c11 -c main.c

Creates main.o

cc -Wall -std=c11 -c file.c

Creates file.o

Then link them

cc -o my-executable main.o file.o

Then you will have a runnable binary called my-executable. If you have an IDE, there will be an equivalent way to do the above, but it will be IDE dependent.

like image 43
JeremyP Avatar answered Sep 18 '25 22:09

JeremyP