0

So, say I have something like this:

main.cpp

#include "main.h"

int main() {
    displayMessage();
    return 0;
 }

main.h

#include <stdio.h>
#include <iostream>

display.cpp

#include "display.h"

void displayMessage() {
    std::cout << "HELLO!\n";
}

display.h

void displayMessage();

How could I include all of them together without being deeply nested? I just started programming a week ago and trying to start early before college starts this upcoming Fall.

John G
  • 1
  • 1
  • 1
  • 2

2 Answers2

1

First giving main a header just to include its headers is a little over the top so I would avoid that.

Something like this:

main.cpp

#include <cstdio>
#include <iostream>

#include "display.h"

int main() {
    displayMessage();
    return 0;
 }

display.cpp

#include "display.h"

void displayMessage() {
    std::cout << "HELLO!\n";
}

display.h

// prevent including the same header twice
#ifndef MY_PROJECT_DISPLAY_H
#define MY_PROJECT_DISPLAY_H

void displayMessage();

#endif // MY_PROJECT_DISPLAY_H

Then compile each .cpp file to an object file:

g++ -c -o main.o main.cpp
g++ -c -o display.o display.cpp

Then link the objects to make an executable:

g++ -o my_program_name main.o display.o

You may want to set some useful flags while compiling (highly recommended):

g++ -std=c++14 -Wall -Wextra -pedantic-errors -c -o main.o main.cpp
g++ -std=c++14 -Wall -Wextra -pedantic-errors -c -o display.o display.cpp
Galik
  • 47,303
  • 4
  • 80
  • 117
0

Its better if you don't create and include main.h in main.cpp. Instead include display.h in main.cpp.

Also "Modern C++" encourages to use C++ style include headers <cstdio> instead of C style ones stdio.h.

And yes, welcome to programming. It's fun. :)

  • So move everything into one header file instead of multiple header files? – John G May 01 '17 at 05:01
  • No. First lets understand why do we need header files. Header files only say the interface of functions and data structures. They don't have any implementation details. For example we have a header file **music.h** having a function **void play_music()** but it does not say how to play music. Now we add this implementation of how to play music in a separate file **music.cpp**. Now we can include **music.h**, in the file having **main** function (also called a client) to call the play_music function. In this way you can create multiple headers/implementation files for different functionalities. – Partha Pratim Mukherjee May 01 '17 at 05:17