在Visual 2022中,对于项目A,我希望设置项目B,它引用项目A(重用现有代码)的头文件(.h
)和源文件(.cpp
)。但是,我不知道如何正确地指向现有文件才能使Project B成功构建。使用#include "../unittest.h"
并在设置中设置路径->C/C++->附加包含目录无效(Error LNK2019,Error LNK1120)。该项目是一个控制台应用程序项目。
引用文件的内容如下所示:
unittest.h (项目A)
#pragma once
int ret1(void);
unittest.cpp (项目A)
#include "unittest.h"
int ret1(void)
{
return 1;
}
main.c (项目B)
#include <stdio.h>
#include "../unittest.h" // -> This doesn't seem to be enough
int main()
{
char temp[10];
sprintf(temp, "%d", ret1()); // Here I want to use the external function
printf(temp);
}
任何关于如何包含外部文件的帮助都将不胜感激。
构建日志:
Rebuild started...
1>------ Rebuild All started: Project: TestProject, Configuration: Debug x64 ------
1>TestProject.cpp
1>TestProject.obj : error LNK2019: unresolved external symbol "int __cdecl ret1(void)" (?ret1@@YAHXZ) referenced in function main
1>C:\Users\dirtl\Documents\Visual Studio 2022\Projects\TestProject\x64\Debug\TestProject.exe : fatal error LNK1120: 1 unresolved externals
1>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(1094,5): error MSB6006: "link.exe" exited with code 1120.
1>Done building project "TestProject.vcxproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
发布于 2022-11-07 09:28:30
为了允许函数重载,C++编译器使用。
这意味着C++函数的实际名称与预期的不完全相同,因为它还包含有关参数等的信息。
要使C++函数可以从C(或其他兼容语言)调用,必须将C++函数声明为extern "C"
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
int ret1(void);
#ifdef __cplusplus
}
#endif
如果您像上面一样修改了头文件,并确保它包含在C++源文件中,那么这个函数就不会有一个损坏的名称,并且可以从C.
https://stackoverflow.com/questions/74344297
复制相似问题