In C programming, what is an `undefined reference`error when compiling?

I have the following simple program that I am trying to compile on linux ubuntu.

Main.c

 #include <stdio.h> #include "Person.h" int main() { struct Person1 p1 = Person1_Constructor(10, 1000); } 

Person.c

 #include <stdio.h> #include "Person.h" struct Person1 Person1_Constructor(const int age, const int salary) { struct Person1 p; p.age = age; p.salary = salary; return p; }; 

Person.h

 struct Person1 { int age, salary; }; struct Person1 Person1_Constructor(const int age, const int salary); 

Why can I get the following error ?

 /tmp/ccCGDJ1k.o: In function `main': Main.c:(.text+0x2a): undefined reference to `Person1_Constructor' collect2: error: ld returned 1 exit status 

I am using gcc Main.c -o Main to compile.

+6
source share
2 answers

When you link the program, you need to provide both Main.o and Person.o as inputs.

The assembly is usually performed in two stages (1) compilation and (2) binding. To compile your sources, follow these steps:

 $ gcc -c -o Main.o Main.c $ gcc -c -o Person.o Person.o 

Then the resulting object files must be linked into one executable file:

 $ gcc -o Main Main.o Person.o 

For small projects of several compilation units like yours, both steps can be performed with a single gcc call:

 $ gcc -o Main Main.c Person.c 

both files must be specified because some characters in Person.c are used by Main.c

For large projects, the two-step process allows you to compile only what was changed during the generation of the executable file. This is usually done through a Makefile.

+4
source

The problem is probably because you only compile Main.c when you need to compile Main.c and Person.c at the same time. Try compiling it as gcc Main.c Person.c -o MyProgram .

Whenever you have several files, all of them must be specified at compilation to resolve external links, as is the case here. The compiler spits out object files that will later be associated with the executable. Check out this makefile guide: Make a tutorial on files This helps automate this process.

+1
source

Source: https://habr.com/ru/post/986399/


All Articles