简体   繁体   中英

C++ Code Compiles with .cpp Source but not .c

In Visual Studio 2008, using C++, I tried to build a DLL using the instructions at http://msdn.microsoft.com/en-us/library/ms235636.aspx , except I named a source file with an extension of ".c" rather than the suggested ".cpp".

With an extension of .c, the compiler throws 37 errors. With an extension of .cpp, the DLL builds successfully.

What difference does the extension of a source file make?

Here is the full code:

// MathFuncsDll.cpp
// compile with: /EHsc /LD

#include "MathFuncsDll.h"

#include <stdexcept>

using namespace std;

namespace MathFuncs
{
    double MyMathFuncs::Add(double a, double b)
    {
        return a + b;
    }

    double MyMathFuncs::Subtract(double a, double b)
    {
        return a - b;
    }

    double MyMathFuncs::Multiply(double a, double b)
    {
        return a * b;
    }

    double MyMathFuncs::Divide(double a, double b)
    {
        if (b == 0)
        {
            throw new invalid_argument("b cannot be zero!");
        }

        return a / b;
    }
}




// MathFuncsDll.h

namespace MathFuncs
{
    class MyMathFuncs
    {
    public:
        // Returns a + b
        static __declspec(dllexport) double Add(double a, double b);

        // Returns a - b
        static __declspec(dllexport) double Subtract(double a, double b);

        // Returns a * b
        static __declspec(dllexport) double Multiply(double a, double b);

        // Returns a / b
        // Throws DivideByZeroException if b is 0
        static __declspec(dllexport) double Divide(double a, double b);
    };
}

当扩展名为.c ,编译器会将其编译为C。当扩展名为.cpp ,它将编译为C ++。

编译器可能会将文件解释为C文件,而不是C ++文件。

The compiler (driver program) guesses at the source language based on the extension, assuming C for .c and C++ for .cpp . You can override that guess with -Tp to force C++ or -Tc to force C. If you want that for all the files you pass instead of just one, capitalize ( -TP or -TC ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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