Mohammed Mahmood
Mohammed Mahmood

Reputation: 1

Separating a function into a different file in C

In my code, I have a few void functions that use global variables.

int i =0;

void increment()
{
      i++;
}

int main()
{
      increment();
      printf("i = %i\n",i)
}

I want to separate the functions into different files, so I move int i; into a header file, and declare the void function there. e.g

(in my header file)

int i = 0;
void increment(); 

(in main file)

#include "header.h"

int main()
{
      increment();
      printf("i = %i\n",i);
}

When I compile, I get an undefined reference to increment. What do I need to do to fix this?

Upvotes: 0

Views: 308

Answers (4)

Pras
Pras

Reputation: 4044

Undefined reference error is due to increment is declared in header file but it is not defined in any of your c files I suggest you code like below:

(in my header file)

EXTERN int i;
void increment(); 

(in main file)

#define EXTERN
#include "header.h"

int main()
{
      increment();
      printf("i = %i\n",i);
}

(in a new c file)

#define EXTERN extern
#include "header.h"

void increment()
{
    i++;
}

Upvotes: 0

David C. Rankin
David C. Rankin

Reputation: 84642

Continuing from the comment, you want to avoid the use of global variables unless they are absolutely required. You can just as easily separate your function into a separate files and pass a pointer to the integer i as a parameter to increment. It takes little extra effort, and avoids a number of pitfalls, e.g.

increment.h

void increment (int *i);

increment.c

void increment (int *i)
{
    (*i)++;
}

main.c

#include <stdio.h>

#include "increment.h"

int main (void) {

    int i = 0, j;

    for (j = 0; j < 5; j++) {  /* simple loop to call increment 5-times */
        increment (&i);
        printf ("call %d, i : %d\n", j, i);
    }

    return 0;
}

Example Compile

$ gcc -Wall -Wextra -pedantic -std=gnu11 -Ofast increment.c -o bin/main main.c

Example Use/Output

$ ./bin/main
call 0, i : 1
call 1, i : 2
call 2, i : 3
call 3, i : 4
call 4, i : 5

Look things over and let me know if you have further questions.

Upvotes: 2

Nguai al
Nguai al

Reputation: 958

In your header file, myheader.h,

 extern int i;
 extern void increment();

In increment.c,

 #include "myheader.h"

 void 
 increment()
 {
      i++;
 }

In main.c,

#include <stdio.h>
#include "myheader.h"
int i = 0;

int main()
{
     increment();
     printf("i = %i\n",i);
}

Upvotes: 2

Mohanad S. Hamed
Mohanad S. Hamed

Reputation: 301

This worked with me:

header.h

int i = 0;
void increment()
{
    i++;
}

main.cpp

#include "header.h"

int main(){

    increment();
    printf("i = %i\n",i);

    return 0;
}

Upvotes: 0

Related Questions