如何在另一个.cpp文件中使用函数?

时间:2013-08-28 12:12:17

标签: c++ visual-studio function visual-c++ project

我正在Visual Studio 2013 Preview中创建一个项目,其中包含我正在学习C ++的教程中的代码。项目中的主文件包含一个程序,该程序能够启动同一项目中另一个.cpp文件中定义的函数。它的代码如下:

#include "stdafx.h"
#include <iostream>
#include "Comments.cpp"
#include "Structure of a Program.cpp"

int structure(void);
void comment(void);

int main()
{
    using namespace std;
    cout << "This project contains files related to Chapter 1 of Learn CPP
        Tutorials\n" << endl;
    cout << "Please type in the tutorial number to view its output:\n" << 
        "1 - Structure of a Program\n" <<
        "2 - Comments\n" <<
         "3 - A First Look at Variables (and cin)\n" <<
        "4 - A First Look at Functions\n" <<
        "5 - A First Look at Operators\n" <<
        "6 - Whitespace & Basic Formatting\n" <<
        "7 - Forward Declarations\n" <<
                "8 - Programs With Multiple Files\n" <<
        "9 - Header Files\n" <<
        "10 - A First Look at the Preprocessor\n" <<
        "11 - How to Design your First Programs\n" << endl;
    int x;
    cin >> x;
    if (x == 1)
    {
        structure();
    }
    if (x == 2)
    {
         comment();
    }
    cout << "Thank you for using this program. Good bye." << endl;
    return 0;
}

我遇到的问题是,当我构建程序时,总会出现一个错误,即我正在启动的函数已经定义,即使它们不是这样。基本上,我需要有关如何启动位于不同.cpp文件但位于同一项目中的函数的帮助。

由于

1 个答案:

答案 0 :(得分:0)

永远不要包含.cpp文件!

通常,包含.cpp文件将导致重新编译不应编译或不编译多次的代码(因此链接错误)。另一方面,在.h文件中你放置了几次可能被编译的声明和其他东西,对于每个.h文件的包含,它们将大致编译一次。

在这种情况下,由于您已声明了structure()和comment(),因此您可能不需要将.cpp包含替换为任何内容。

相关问题