cpp 文件不使用 cl 编译,但在 Visual Studio 中编译得很好

Posted

技术标签:

【中文标题】cpp 文件不使用 cl 编译,但在 Visual Studio 中编译得很好【英文标题】:cpp File not compiling with cl, but compiles just fine inside Visual Studio 【发布时间】:2016-01-11 15:46:06 【问题描述】:

我遇到了以下代码无法使用 CL (VS CMD) 编译的问题。 它没有编译,而是给了我错误 LN2019。 在 VS 中编译相同的代码,编译没有错误。

#include <windows.h>

LRESULT CALLBACK
MainWindowCallback( HWND   Window,
                    UINT   Message,
                    WPARAM WParam,
                    LPARAM LParam)

    LRESULT Result = 0;

    switch(Message)
    
        case WM_SIZE:
        
            OutputDebugStringA("WM_SIZE\n");
         break;

        case WM_DESTROY:
        
            OutputDebugStringA("WM_DESTROY\n");
         break;

        case WM_CLOSE:
        
            OutputDebugStringA("WM_CLOSE\n");
         break;

        case WM_ACTIVATEAPP:
        
            OutputDebugStringA("WM_ACTIVATEAPP\n");
         break;

        default:
        
            // OutputDebugSTringA("default\n")
            Result = DefWindowProc(Window, Message, WParam, LParam);
         break;
    

    return(Result);


int CALLBACK
WinMain(HINSTANCE Instance,
        HINSTANCE PrevInstance,
        LPSTR     CommandLine,
        int       ShowCode)

    WNDCLASS WindowClass = ;

    WindowClass.style = CS_OWNDC|CS_HREDRAW|CS_VREDRAW;
    WindowClass.lpfnWndProc = MainWindowCallback;
    WindowClass.hInstance = Instance;
    // WindowClass.hIcon;
    WindowClass.lpszClassName = "FooWindowClass";

    return(0);

我将问题追踪到第 36 行:

Result = DefWindowProc(Window, Message, WParam, LParam);

当我注释掉这一行时,文件编译得很好。 用于编译的 cl 命令也很标准:

cl -Zi Foo.cpp

我错过了一些 cl 参数吗?

【问题讨论】:

C 不是 C++ 不是 C! 从前缀LN,我猜这是一个链接器错误:DefWindowProc 定义在哪里? 您缺少很多 VisualStudio 传递给 cl 的开关。项目属性页面之一显示生成的命令行。 如果您收到错误,请发布整个错误消息,不要修改。 【参考方案1】:

您必须与 user32.lib 链接:

cl Foo.cpp user32.lib

【讨论】:

是的,它做到了。认为这将是一个这样的参数。知道为什么在使用 cl 时它不会自动包含 user32.lib 吗?与 VS 本身不同? @kazaamjt:Visual Studio 也不会自动包含任何 CL 参数。它使用项目设置中指定的那些【参考方案2】:

错误Error LN2019 没有“主”(您似乎已将其命名为WinMain)。

另请参阅:error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

【讨论】:

以上是关于cpp 文件不使用 cl 编译,但在 Visual Studio 中编译得很好的主要内容,如果未能解决你的问题,请参考以下文章

为 cl.exe (Visual Studio Code) 指定命令行 C++ 版本

如何设置发布/调试模式以使用 Microsoft C++ 工具集在命令提示符处编译 cpp 文件

使用 clang-cl 在 Visual Studio 2019 中使用 Openmp 4/5

强制包含可以与 Visual C++ 中的预编译头一起使用吗?

在 Visual Studio 中编译与在命令行中使用 cl 编译

Visual C++ 2012 (x86) 中可能的编译器错误?