C++ 无法从不同的文件错误LNK2005和致命错误LNK1169调用任何内容

C++ 无法从不同的文件错误LNK2005和致命错误LNK1169调用任何内容,c++,C++,我尝试链接其他包含函数的文件,并在主文件中调用它 #include <iostream> #include "test1.cpp" int main() // main.cpp file { fun(); return 0; } #include <iostream> //test1.cpp file void fun() { std::cout << "

我尝试链接其他包含函数的文件,并在主文件中调用它

#include <iostream>
#include "test1.cpp"
    int main()     // main.cpp file
    {
        fun();
        return 0;
    }

#include <iostream>   //test1.cpp file
void fun()
{
    std::cout << "text";
}

您不应该在另一个文件中包含.cpp文件。如果这样做,函数将声明两次,这是导致链接错误的原因


要实现您的目标,请使用头文件.h,在该文件中您将仅声明函数的原型,并将此头文件包含在main.cpp中。

正确的方法是使用3个文件:

main.cpp

#include <iostream>
#include "test1.h" // notice the .h file extension instead of .cpp
int main()     // main.cpp file
{
    fun();
    return 0;
}

有关这方面的更多信息,您可以阅读更多信息。

链接器错误意味着问题不在于代码,而在于如何构建代码。如何构建它?好吧,我只需创建一个空项目,然后在/source files dir中生成.cpp文件,然后只需按“local windows debugger”。@最大的\u prime\u是\u 463035818,但是,瞧,问题出在代码中。问题是函数定义了两次,多个声明不是问题。
#include <iostream>
#include "test1.h" // notice the .h file extension instead of .cpp
int main()     // main.cpp file
{
    fun();
    return 0;
}
#include <iostream>
void fun()
{
    std::cout << "text";
}
// a function declaration
void fun();