carouz
carouz

Reputation: 1

How to use gcc correctly from the ubuntu terminal?

I'm try to compile a .c file from the terminal using gcc. The file includes a personal library where a function is defined. This library.h and the .c file are in the same directory.

I get the following message error

undefined reference to `function'"

Should I use another argument as:

gcc -o nameoutput filename

or should I place the library.h in another directory?

Upvotes: 0

Views: 184

Answers (2)

John Bode
John Bode

Reputation: 123488

"Undefined reference" means that the linker can't find the object file containing the compiled body of function; it doesn't have anything to do with the .h file.

I sounds like you have a situation where library.h and library.c are in one directory, and main.c is in a different directory. If that's the case, then your command line will need to look something like this:

gcc -o program -I /path/to/library main.c /path/to/library/library.c 

-I /path/to/library means that gcc will look for .h files in that path as well as the standard include paths. That also allows you to write

#include "library.h"

instead of

#include "/path/to/library/library.h"

in any code that needs it.

Upvotes: 1

Paul R
Paul R

Reputation: 212979

Assuming you have library.c, library.h and main.c in your current working directory:

$ gcc -Wall main.c library.c -o my_program

and then to run it:

$ ./my_program

Upvotes: 1

Related Questions