【问题标题】:Visual Studio 2022 doesn't want to linkVisual Studio 2022 不想链接
【发布时间】:2022-01-02 18:55:09
【问题描述】:

我在使用 Visual Studio 和使用 g++ 完美编译的代码时遇到问题。

实际上,我有这 3 个文件(这是重现问题的最少代码...):

Source2.h

#pragma once

#include <stdio.h>
void test(double arg1, double arg2, int arg3);

来源.c

#include "Source2.h"

int main(int argc, char* argv[]) {
    test(10.1, 12.0, 13);

    return 0;
}

Source2.cpp

#include "Source2.h"
#include "Eigen/Dense"
#include "Eigen/Eigenvalues"

using namespace Eigen;

void test(double arg1, double arg2, int arg3) {
    printf("ok\n");
}

我注意到将所有扩展名更改为 .cpp 而不是 .c/.cpp 可以解决问题,但我不明白为什么在 g++ 正常工作时需要它...

【问题讨论】:

  • Visual Studio 是否对 .c 和 .cpp 文件使用了不同的编译器?你为什么要混合它们?
  • 您没有在编辑中回答您自己的问题吗? g++ 将文件编译为 c++
  • @WeatherVane 我编辑了这个问题......老实说,我不知道 Visual Studio 是否使用不同的编译器。实际上,在我的代码中,我的文件包含简单的 C 代码,而其他文件则使用 C++ 函数,因此它们使用 .cpp 扩展名保存。我在 Ubuntu 中使用 g++ 命令编译没有问题,这是因为它不关心扩展名吗?
  • g++ 可以编译任何 .c 或 .cpp 文件,但它们只会被视为 C++ 文件,而 gcc 可以编译任何 .c 或 .cpp 文件,但它们将分别被视为 C 和 C++,和 AFAIK 同样适用于 Visual Studio。

标签: c linker visual-studio-2022


【解决方案1】:

当您链接 .cpp 和 .c 时,您需要在 .h 文件中添加以下内容

#if __cplusplus 
extern "C" void test(double arg1, double arg2, int arg3);
#else
void test(double arg1, double arg2, int arg3);
#endif

因为 C++ 期望否则会出现损坏的签名,即包含有关参数的更多信息以及其他一些内容。

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2022-09-25
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2023-03-31
    • 2022-08-08
    相关资源
    最近更新 更多