【问题标题】:Linker error for adding static library添加静态库的链接器错误
【发布时间】:2018-01-09 07:43:36
【问题描述】:

我正在按照教程 here 创建一个静态库并将其用于另一个项目。所以我想创建一个 .lib 文件并将其用于另一个项目。

静态库项目:

MyMathLib.h

#define PI 3.1415;
double PowerOf2(double UserNumber);
double PowerOf3(double UserNumber);
double CircleArea(double UserRadius);
double CircleCircum(double UserRadius);

MyMathLib.cpp

#include "stdafx.h"
#include "MyMathLib.h"

double PowerOf2(double UserNumber) { return UserNumber * UserNumber; }
double PowerOf3(double UserNumber) { return UserNumber * UserNumber * UserNumber; }
double CircleArea(double UserRadius) { return UserRadius * UserRadius * PI; }
double CircleCircum(double UserRadius) { return 2 * UserRadius * PI; }

对于第二个项目,我做了以下工作:

  • 添加 MyMathLib vc 项目

  • 通用属性 -> 参考 -> 添加新参考

  • C/C++ -> 常规 -> 附加包含目录。

这是试图调用库的 C 文件:

MyApps1.c

#include <stdio.h>
#include "MyMathLib.h"

int main()
{
    double p2 = 10.0;
    double radius = 4.0;

    printf("The number %.2f to the power of 2 is %.2f. \n", p2, PowerOf2(p2));
    printf("A circle with a radius of %.2f, the area is %.2f. \n", radius, CircleArea(radius));

    return 0;
}

我得到的错误是:

1>------ Build started: Project: MyApps1, Configuration: Debug Win32 ------
1>MyApps1.obj : error LNK2019: unresolved external symbol _PowerOf2 referenced in function _main
1>MyApps1.obj : error LNK2019: unresolved external symbol _CircleArea referenced in function _main
1>c:\users\bandika\documents\visual studio 2013\Projects\MyApps1\Debug\MyApps1.exe : fatal error LNK1120: 2 unresolved externals
========== Build: 0 succeeded, 1 failed, 1 up-to-date, 0 skipped ==========

所以某处存在链接错误。我曾尝试转到 MyApps1 属性 -> 链接器 -> 输入 -> 附加依赖项,但我认为我无法为 MyMathLib 添加 .lib 文件。知道我错过了什么吗?

【问题讨论】:

标签: c++ c visual-studio linker


【解决方案1】:

它与您的静态库与第二个项目的链接有关。

在“配置属性 -> 链接器 -> 输入 -> 附加依赖项”中添加生成的静态库名称没有任何问题。 它应该可以解决链接问题。

您在使用此选项后是否遇到任何其他问题?

【讨论】:

    【解决方案2】:

    您没有将第二个文件添加到 VS 中的项目中。

    【讨论】:

    • 这是有道理的,它找不到实现,所以 .c 一定没有被链接。但我相信当我执行“附加包含目录”时,我添加了 .h 和 .c 文件所在的目录。我认为我也不应该手动添加文件。
    • 在链接中包含无关紧要。在 VS 中,这是一个非常常见的错误。您需要将.c 文件添加到项目,否则makefile 生成器将不知道它的任何信息
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多