Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking custom header files when compiling c++

When compiling a C++ program on linux using g++, how do you link in your own header files?

For example I have a file with the following includes:

#include <stdlib.h>
#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
#include "3DCurve.h"

When I compile using the following command:

 g++ -lm -lglut -lGL -o 3dcurve Example_8_1.cpp

I get the following error:

undefined reference to 'draw3Dcurve(double, double, double, double, double, double)'

How do I link the the 3DCurve.h file into the compiler? The header file and its implementation sit in the same folder as the file I'm compiling. My understanding is that the compiler should just find it, if it is sitting in the same folder.

What am I not getting?

like image 797
Martinffx Avatar asked Apr 29 '12 07:04

Martinffx


2 Answers

One doesn't link to header files, one just includes them. But if the header file has a corresponding implementation file, you either have to include that in the compilation line, or make an object file out of that, and include that in the compilation line. From your error, it looks like you have an implementation file that hasn't been dealt with appropriately.

Assuming the implementation if DCurve.h is called 3DCurve.cpp then you could do this:

g++ -lm -lglut -lGL -o 3dcurve 3DCurve.cpp Example_8_1.cpp

Other options are to make an object file 3DCurve.o using the -c g++ option, and then

g++ -lm -lglut -lGL -o 3dcurve 3DCurve.o Example_8_1.cpp

Or, make a shared or static library and use it like you would another 3rd party library.

like image 134
juanchopanza Avatar answered Sep 23 '22 22:09

juanchopanza


The compiler won't "just find" the implementation.

You've included the header 3DCurve.h, and GCC finds it using the search path:

GCC looks for headers requested with #include "file" first in the directory containing the current file, then in the directories as specified by -iquote options, then in the same places it would have looked for a header requested with angle brackets.

For the implementation 3DCurve.cpp, you have to compile and link it in your command, e.g.:

 g++ Example_8_1.cpp 3DCurve.cpp -o 3dcurve -lm -lglut -lGL
like image 40
stylishtoupee Avatar answered Sep 25 '22 22:09

stylishtoupee