0

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?

3
  • 2
    format your text do code properly, and post a minimal reproducible example Commented Feb 11, 2022 at 15:00
  • 2
    You need to also compile and link functions.c. gcc main.c functions.c -o main Commented Feb 11, 2022 at 15:05
  • 1
    The macro needs to be #define ADD(n1, n2) ((n1) + (n2)) so that it works correctly when called with arguments such a ADD(a & b, c | d) or other expressions involving operators with lower precedence than +, or when it is used in an expression involving operators with higher precedence than +: x = ADD(a, b) * ADD(c, d). Commented Feb 11, 2022 at 15:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It's working now!
2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.