所以我想制作一个共享库,并测试它是如何工作的...但我只是不明白我在这里做错了什么...
main.cpp:
//main.cpp
#include <iostream>
__declspec(dllimport) int foo(int);
int main() {
std::cout << foo(5) << std::endl;
}
共享.cpp:
shared.cpp
__declspec(dllexport) int foo(int k) {
return k;
}
每次我尝试构建时,都会失败并显示以下输出: 输出:
[build] MSBuild version 17.7.2+d6990bcfa for .NET Framework
[build]
[build] MnShared.vcxproj -> D:\Programs\tst\mn\build\Debug\MnShared.dll
[build] main.cpp
[build] main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) int __cdecl foo(int)" (__imp_?foo@@YAHH@Z) referenced in function main
[build] D:\Programs\tst\mn\build\Debug\MN.exe : fatal error LNK1120: 1 unresolved externals
[proc] The command: "E:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" --build d:/Programs/tst/mn/build --config Debug --target ALL_BUILD -j 10 -- exited with code: 1
[driver] Build completed: 00:00:02.045
[build] Build finished with exit code 1
注意:shared.cpp 和 main.cpp 位于同一项目中,并且在同一目录中构建
CMakeLists.txt:
cmake_minimum_required(VERSION 3.8)
project(MN CXX)
add_executable(MN main.cpp)
add_library(MnShared SHARED shared.cpp)
在
target_link_libraries(MN PRIVATE MnShared)
底部添加CMakeLists.txt
解决了问题。