Need help in Header files in C

I can’t seem to understand why I get this kind of error and don’t know how to fix it:


Please need help. Here is the code

main.c

#include <stdio.h>

#include "functions.h"  

int main() {

    printf("%d\n", add(2,6));

    printf("%d\n", ADD(3,7));

    person engineer_man;

    engineer_man.age = 32;

    printf("Engineer man's age is: %d\n", engineer_man.age);

    return 0;

}

functions.c

#include "functions.h"

int add(int n1, int n2){
    return n1 + n2;
}

functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int add(int , int);

#define ADD(n1,n2) n1 + n2

typedef struct {
    int age;
    char *name;
} person;

#endif

How did you compile?

I just clicked the run code icon in vs code

I suspect this is not compiled correctly. You should figure out what that button does.

I don’t really get it. I tried commenting out “printf(”%d\n", add(2,6));" statement and it compiles fine. Maybe that part is the problem.

The problem seems to be that your code is not compiling correctly. Your code in the second file doesn’t seem to be compiled and linked to the code in the file with main.

Undefined reference means that your code in main doesn’t know where do find the compiled code to run the function ‘add’.

Do you have any suggestions for this? I am struggling to find the solution

You need to figure out what that button does. How is it compiling the code?

@JeremyLT thank you so much I figured it out. I am not really sure if I am doing it right because I am new to this header stuff.

Is it correct that I just added "#include “functions.c” in the main.c? it seems to remove the error and compiled correctly. YT tutorials don’t seem to do that.

No. You should not do that. That’s not how header files are intended to be used.

Oh okay, I’ll try something else

You need to figure out how that button is compiling your code, because its doing it wrong.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.