简体   繁体   English

在这种情况下,如何包含所有.cpp和头文件?

[英]How do I include all .cpp and header files in this situation?

So, say I have something like this: 所以,说我有这样的事情:

main.cpp main.cpp

#include "main.h"

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

main.h 主文件

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

display.cpp display.cpp

#include "display.h"

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

display.h 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. 首先给main一个标头只是为了包含它的标头在顶部有点高,所以我会避免这种情况。

Something like this: 像这样:

main.cpp main.cpp

#include <cstdio>
#include <iostream>

#include "display.h"

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

display.cpp display.cpp

#include "display.h"

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

display.h 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: 然后将每个.cpp文件编译为一个目标文件:

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 . 如果您不创建main.h并将其包含在main.cpp则更好。 Instead include display.h in main.cpp . 而是在main.cpp包括display.h

Also "Modern C++" encourages to use C++ style include headers <cstdio> instead of C style ones stdio.h . 另外,“现代C ++”鼓励使用C ++样式包含标头<cstdio>而不是C样式的stdio.h

And yes, welcome to programming. 是的,欢迎进行编程。 It's fun. 很有趣。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM