C ++项目中的两个main()将无法构建

时间:2013-09-01 14:58:41

标签: c++ visual-c++

我最近下载了Microsoft Visual C ++ 2010 Express以尝试学习C ++,而我正在遇到问题。我之前使用过Java和Microsoft Visual C ++似乎与它类似。

所以我的问题是我创建了一个名为Project的项目,我在项目中有两个文件(HelloWorld.cpp和PowersOfTwo.cpp)。 HelloWorld.cpp的代码如下:

 /* 
Hello World File
*/

#include <iostream>
using namespace std;

int main()
{
    cout<< "Hello, World" << endl;

    return 0;

}

PowersOfTwo.cpp代码如下:

    /*
This program generates the powers of two
until the number that the user requested
*/

#include <iostream>
using namespace std;

int raiseToPower(int n, int k);

int main()
{
    int limit;
    cout << "This program lists the powers of two. " << endl;
    cout << "Enter exponent limit: ";
    cin >> limit;

    for (int i = 0; i <= limit; i++)
    {
        cout << "2 to the " << i << " = " << raiseToPower(2, i) << endl;
    }

    return 0;
}

/* Function for raiseToPower */

int raiseToPower(int n, int k)
{
    int result = 1;
    for (int i = 0; i < k; i++)
    {
        result *= n;
    }
    return result;

}

基本上,我尝试在没有调试PowersOfTwo.cpp文件的情况下启动但最终导致致命错误,指出已经在HelloWorld.obj中定义了_main。这是否意味着我不能在同一个项目中有两个带有main方法的文件(与eclipse相反,当我有两个带有main方法的文件时)。这是否意味着我每次都必须创建一个新项目才能使一个不​​相关的程序工作?

2 个答案:

答案 0 :(得分:2)

是。尽管Java中的任何数量的类都可以具有“主”功能,但在C ++程序中只能出现一个“主”功能。

答案 1 :(得分:2)

在Visual Studio for C ++中,“项目”是“程序”。每次要创建新程序,新的.exe文件时,都必须创建一个新项目。您不能使用单个项目来创建具有不同C ++文件的多个不同程序。

“解决方案”是一组项目,您可以在解决方案中拥有许多程序。为所有实验创建一个解决方案,然后在每次要编写新程序时添加一个新项目。

相关问题