Compiling .h with .cpp on linux?

I have been compiling on linux using g++ in the terminal. I am not using any IDE's which I can if I want with netbeans, but I prefer not to. So my question is what other commands will I have to use if I want to #include a header file as a directive in my main.cpp? For example, suppose I create a main.cpp, then a example.h and example.cpp, I then #include "example.h" into main, trying to compile:
g++ ~/Desktop/main.cpp -o ~/Desktop/main
will bring me errors displaying example.h does not exist.

I am still learning a lot with linux with a bunch of commands from making files, moving, opening, etc. I barely touch my mouse for anything, its really cool.
Last edited on
closed account (ihq4izwU)
In you main.cpp, try changing your code from #include "example.h" and make it #include "DirLocation/example.h" .

I'm wrong right? Well, I'm also still starting using linux but I preferred understanding the entire environment first before digging deeper with commands later, though I'm starting with the basic ones... >:)
Last edited on
gcc has a -I option that you use to specify the include path.

If example.h was in ../project/headers, you'd specify:
g++ -I../project/headers ~/Desktop/main.cpp -o ~/Desktop/main

But you're really making a rod for your own back by not working in the project directory.

If your files are in ~/Desktop, you can go to ~/Desktop and run (you don't need a makefile):
make main

That will execute the command:
g++ main.cpp -o main

If you want to specify options with that, you do this for example:
make main CXXFLAGS="-g -I../project/headers -I../extra/headers"

If main is already built and main.cpp hasn't changed, you'll get:
make: 'main' is up to date.
Last edited on
I recommend you to use makefile. Create a file named "Makefile" and put the following in it:

CC = g++

main: main.o example.o
TAB $(CC) main.o example.o -o main -g
main.o: main.cpp example.h
TAB $(CC) main.cpp -c -g
example.o: example.cpp example.h
TAB $(CC) example.cpp -c -g

where TAB is your TAB key.
You can see basic introduction to make here:

Or if you want to compile from terminal, this command should work:
gcc -o main main.cpp example.cpp
Last edited on
Topic archived. No new replies allowed.