Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;带有extern“的两个文件出现lnk2005错误;",;,为什么?_C++_C++ Cli_Export_Command Line Interface_Lnk2005 - Fatal编程技术网

C++ C++;带有extern“的两个文件出现lnk2005错误;",;,为什么?

C++ C++;带有extern“的两个文件出现lnk2005错误;",;,为什么?,c++,c++-cli,export,command-line-interface,lnk2005,C++,C++ Cli,Export,Command Line Interface,Lnk2005,我有一个带有外部“C”函数的CPP。如果它们都在一个文件中,那么一切都很好。我想把这些功能分成不同的文件,只是为了组织的目的 假设我有两个文件: 文件_One.cpp #pragma once #include "stdafx.h" #include <windows.h> #include "Functions.h" #include "Variables.h" #include <string> #include "File_Two.cpp" extern "C"

我有一个带有外部“C”函数的CPP。如果它们都在一个文件中,那么一切都很好。我想把这些功能分成不同的文件,只是为了组织的目的

假设我有两个文件:

文件_One.cpp

#pragma once
#include "stdafx.h"
#include <windows.h>
#include "Functions.h"
#include "Variables.h"
#include <string>
#include "File_Two.cpp"

extern "C"
{
    __declspec(dllexport) void MethodOne()
    { 
        MethodTwo();
    }
}
#pragma一次
#包括“stdafx.h”
#包括
#包括“Functions.h”
#包括“Variables.h”
#包括
#包括“File_Two.cpp”
外部“C”
{
__declspec(dllexport)void MethodOne()
{ 
方法二();
}
}
文件2.cpp

#pragma once
#include "stdafx.h"
#include <windows.h>
#include "Functions.h"
#include "Variables.h"
#include <string>

extern "C"
{
    __declspec(dllexport) void MethodTwo()
    { 
    }
}
#pragma一次
#包括“stdafx.h”
#包括
#包括“Functions.h”
#包括“Variables.h”
#包括
外部“C”
{
__declspec(dllexport)void MethodTwo()
{ 
}
}
我尝试过以不同的顺序重新排列include头,甚至在文件_one.cpp中除了文件_two.cpp的include头之外不放置include头,但我总是会遇到相同的错误

1) 错误LNK1169:找到一个或多个多重定义符号

2) 错误LNK2005:_MethodTwo已在文件_One.obj中定义

我到底做错了什么? 我该怎么做才能修好它


谢谢大家!

您可能遇到了问题,因为您将
文件\u two.cpp
文件包含在
文件\u one.cpp
文件中。正在发生的事情是,
File\u two.cpp
File\u one.cpp
正在被编译和链接。但是,由于
File_two.cpp
包含在
File_one.cpp
中,链接器看到了
MethodTwo
的两个副本,因此无法决定使用哪个副本

您应该将声明移动到标题:

文件\u two.h:

extern "C"
{
    __declspec(dllexport) void MethodOne()
}
extern "C"
{
    __declspec(dllexport) void MethodOne();
}
并将其包括在内

File\u one.h:

extern "C"
{
    __declspec(dllexport) void MethodOne()
}
extern "C"
{
    __declspec(dllexport) void MethodOne();
}

然后在各自的
.cpp
文件中定义函数及其主体。源文件中不需要外部“C”。

在另一个cpp文件中包含一个cpp文件通常不是一件好事。如果你这样做,你需要确保所包含的cpp文件没有被编译和链接。我采纳了你的建议,构建了一个头文件,它工作了。