You need to enable JavaScript to run this app. C++出现LNK1120/LNK2019未解析外部符号_main链接错误求助
优惠活动
大模型
产品
解决方案
定价
更多

C++出现LNK1120/LNK2019未解析外部符号_main链接错误求助

LNK1120/LNK2019 未解析_main符号报错问题

报错表现

MSVC链接阶段抛出如下错误:

  • LNK1120:存在1个未解析外部符号
  • LNK2019:找不到被引用的_main符号,引用该符号的函数为int __cdecl invoke_main(void)(修饰名?invoke_main@@YAHXZ)

问题根因

MSVC平台对程序入口函数的硬性要求为:main必须定义在全局命名空间下,是无修饰的全局函数
当前代码将main函数包裹在ceaser命名空间内部,经过C++名称修饰后,实际生成的函数符号和链接器约定查找的_main符号不匹配,因此触发链接失败。

项目现有代码

Cipher.h

#pragma once
#include <string>
#include <algorithm>

namespace ceaser {
    class Cipher
    {
    public:
        std::string FormatMessage(std::string msg);
        std::string Encrypt(std::string msg, int shift);
        std::string Decrypt(std::string encryptedText, int shift);
    };
}

Cipher.cpp

#include "Cipher.h"

namespace ceaser {
    std::string Cipher::FormatMessage(std::string msg) {
        std::transform(msg.begin(), msg.end(), msg.begin(), ::toupper);
        return msg;
    }

    std::string Cipher::Encrypt(std::string msg, int shift) {
        std::string result = "";
        for (int i = 0; i < msg.length(); i++) {
            if (isupper(msg[i]))
                result += char(int(msg[i] + shift - 65) % 26 + 65);
            else
                result += msg[i];
        }
        return result;
    }

    std::string Cipher::Decrypt(std::string encryptedText, int shift) {
        return Cipher::Encrypt(encryptedText, 26 - shift);
    }
}

触发报错的main.cpp

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

namespace ceaser {
    int main()
    {
        Cipher cipher;
        std::string text = "hello world!";
        text = cipher.FormatMessage(text);
        int shift = 4;

        std::string encryptedText = cipher.Encrypt(text, shift);
        std::cout << encryptedText << std::endl;

        std::cout << "decrypting... " + cipher.Decrypt(encryptedText, shift);
        return 0;
    }
}

修复步骤

  • 将main函数移出ceaser命名空间,保证它是全局作用域下的入口函数,匹配链接器查找的符号约定
  • 原代码中输出解密结果的语句采用字符串加号拼接的写法,调整为常规的流链式写法,提升代码可读性
    修正后可正常编译运行的main.cpp代码:
#include <iostream>
#include "Cipher.h"

int main()
{
    ceaser::Cipher cipher;
    std::string text = "hello world!";
    text = cipher.FormatMessage(text);
    int shift = 4;

    std::string encryptedText = cipher.Encrypt(text, shift);
    std::cout << encryptedText << std::endl;

    std::cout << "decrypting... " << cipher.Decrypt(encryptedText, shift) << std::endl;
    return 0;
}

内容的提问来源于stack exchange,提问作者kapz424

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 11:15:03