包括.cpp文件 [英] Including .cpp files

查看:131
本文介绍了包括.cpp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里等地方读过您必须加入.h档案而不是.cpp文件,否则你会得到一个错误。例如,

I have read in places like here that you have to include .h files and not .cpp files, because otherwise then you get an error. So for example

main.cpp

#include <iostream>
#include "foop.h"

int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}

foop.h

#ifndef FOOP_H
#define FOOP_H
int foo(int a);
#endif

foop.cpp

int foo(int a){
    return ++a;
}

有效,但如果我替换 #includefoop .h #includefoop.cpp我得到一个错误(使用Dev C ++ 4.9.9.2,Windows):

works, but if I replace #include "foop.h" with #include "foop.cpp" I get an error (Using Dev C++ 4.9.9.2, Windows):

multiple definition of foo(int)
first defined here

为什么?

推荐答案

include 是从文件复制所有内容这是<> 中的参数),所以当preproccesor完成其工作 main.cpp 将如下所示:

What include does is copying all the contents from the file (which is the argument inside the <> or the "" ), so when the preproccesor finishes its work main.cpp will look like:

// iostream stuff

int foo(int a){
    return ++a;
}

int main(int argc, char *argv[])
{
   int x=42;
   std::cout << x <<std::endl;
   std::cout << foo(x) << std::endl;
   return 0;
}


$ b $ p 因此foo将在 main.cpp ,但是在 foop.cpp 中也存在一个定义,因此编译器因为函数复制而变得混乱。

So foo will be defined in main.cpp, but a definition also exists in foop.cpp, so the compiler "gets confused" becuase of the function duplication.

这篇关于包括.cpp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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