如何链接cpp和h文件在一起? [英] How to link cpp and h files together?

查看:957
本文介绍了如何链接cpp和h文件在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已解决

// Solution:
// foo.c includes foo.h; bar.c includes bar.h
g++ -Wall -Wextra -Werror -pedantic -o foobar foo.cpp bar.cpp

我有两个cpp文件和两个h文件。我有第一个cpp链接到相同名称的h文件,链接到链接到第二个h文件的第二个cpp文件。这是我应该链接文件在一起的方式吗?

I have two cpp files and two h files. I have the first cpp linked to h file of the same name which is linked to the second cpp file that's linked to the second h file. Is this the way I should link the files together?

我的程序不工作。也有错误,但我需要确保这是否是错误的一部分。这是定义/链接cpp和h文件的方式吗?

My program is not working. There are errors too, but I need to make sure if this is part of the error. Is this the way to define/link cpp and h files?

 // file: foo.cpp
 #include "foo.h"

 // file: foo.h
 #include "bar.cpp"

 #include <string>
 #include <sstream>
 #include <iostream>
 using std::cin;
 using std::cout;
 using std::cerr;
 using std::stringstream;
 using std::string;
 using std::endl;

 // file: bar.cpp
 #include "bar.h"

 // file: bar.h
 // ...


推荐答案

完全错误。头文件将包含在cpp文件中。 Cpp文件从不包括在任何东西。通常,头文件包含声明,而cpp文件包含定义。

Completely wrong. Header files are to be included in cpp files. Cpp files are never included in anything. Typically, header files hold declarations, and cpp files hold definitions.

如果程序由2个cpp文件组成,则不包含其中一个。

If youe program consists of 2 cpp files, you do not include one in the other. Instead, you compile them together into a single executable.

我猜你对声明和定义的工作方式有一些误解,或者什么包括什么。我建议你刷一本教科书,或看看一些小的C ++程序在github。

I would guess that you have some misconceptions about the way declarations and definitions work, or what including does. I suggest you brush up with a textbook, or take a look at some small C++ programs on github.

这篇关于如何链接cpp和h文件在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆