0

I realize this has been asked many times, but none of the solutions worked. Here is a simple test code I have.

test.h

#ifdef TEST_H
#define TEST_H

int return_int_3();

#endif

test.c

#include "test.h"

int return_int_3() {
  return 3;
}

main.c

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

int main(void) {
  printf("%d", return_int_3());
  return 0;
}

I don't see what is wrong. One solution was that you have to put the include of "test.h" at the very top which I've done. Other solutions are saying that you have to declare the function before main before using it, which I assume the #include takes care of. So, I'm confused on what the problem is. It does work and produces the right output, but what is the correct way to solve this? I'm using gcc version 10.1.0 if that helps. Thanks.

nZaegik
  • 25
  • 5
  • 11
    did you mean to use `#ifndef` in the header file? The way you have it here would prevent the function declaration from being imported. – Jonathon Anderson Jun 30 '20 at 16:51
  • 1
    By the way, in C, the preferred way to declare and define a function taking no arguments is `int return_int_3(void)`, not `int return_int_3()`. See https://stackoverflow.com/questions/41803937/func-vs-funcvoid-in-c99. – Nate Eldredge Jun 30 '20 at 16:59
  • You have to compile each .c file and link the resulting object files together. gcc does all that at once with `gcc test.c main.c` ... or step by step with `gcc -c main.c`, `gcc -c test.c`, `gcc main.o test.o`. Your source files test.h, test.c, and main.c are ok. – pmg Jun 30 '20 at 17:15

1 Answers1

3

As Jonathon has said your issue is in the test.h file

#ifdef TEST_H
#define TEST_H

int return_int_3();

#endif

As TEST_H is not define the code between ifdef and endif is not used. you need to use ifndef

#ifndef TEST_H
#define TEST_H

int return_int_3();

#endif

Here TEST_H is no def, so the code is used, TEST_H is set so double include is not an issue.

Ôrel
  • 7,044
  • 3
  • 27
  • 46