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.
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
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. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.