Home > front end >  Trying to make a program with header files in C
Trying to make a program with header files in C

Time:02-12

I'm trying to make a program in C that uses header files and I'm getting an error. The program is supposed to add two numbers, add two numbers with a macro, and print a component in a typedef. There are three separate files:

functions.c

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

functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

// function declaration
int add(int, int);

// macro declaration
#define ADD(n1, n2) n1   n2

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

#endif

main.c (This is the main program that uses everything from functions.c and functions.h and prints the result.)

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

int main(void) {
    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);
}

I tried compiling by doing gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c, but then it gave this error:

/usr/bin/ld: /tmp/ccbVAioe.o: in function `main':
/common/home/user/folder/main.c:5: undefined reference to `add'
collect2: error: ld returned 1 exit status

How do I fix this error?

CodePudding user response:

gcc -c functions.c
gcc -o main main.c functions.o

should also work well. I omitted the compiler flags that need to be added in each case, depending on your need.

CodePudding user response:

You never compile functions.c.

You need this:

gcc -g -std=c99 -Wall -Wvla -Werror -fsanitize=address,undefined -o main main.c functions.c
                                                                 you forgot this ^

BTW, you also need to include "functions.h" in "functions.c":

#include "functions.h"

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

Without including "functions.h" your program will build, but if for some reason the function declaration in functions.h doesn't match the function definiton in "functions.c", your program will have undefined behaviour.

  • Related