C++#包括不工作 我试图在C++中包含这样的函数,我不明白为什么它不能工作。我有3个文件

C++#包括不工作 我试图在C++中包含这样的函数,我不明白为什么它不能工作。我有3个文件,c++,header,include,C++,Header,Include,test.cc int test() { std::cout << "This is a test" << std::endl; } #include "test.h" int main() { test(); return 0; } main.cc int test() { std::cout << "This is a test" << std::endl; } #include "test.h" int m

test.cc

int test() {
  std::cout << "This is a test" << std::endl;
}
#include "test.h"

int main() {

    test();
    return 0;
}
main.cc

int test() {
  std::cout << "This is a test" << std::endl;
}
#include "test.h"

int main() {

    test();
    return 0;
}
这是我得到的错误和我使用的命令

c++ main.cc -o main
Undefined symbols for architecture x86_64:
  "test()", referenced from:
      _main in main-12ba52.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

函数测试的定义具有未定义的行为,因为它虽然具有返回类型int,但不返回值

int test() {
  std::cout << "This is a test" << std::endl;
}
int测试(){

std::cout函数测试的定义具有未定义的行为,因为它虽然具有返回类型int,但不返回值

int test() {
  std::cout << "This is a test" << std::endl;
}
int测试(){

std::cout您应该将以下内容添加到
test.cc

#include "test.h"
#include <iostream>
#包括“test.h”
#包括

并确保您正在使用
test.cc构建/链接

您应该将以下内容添加到
test.cc

#include "test.h"
#include <iostream>
#包括“test.h”
#包括

并确保您正在构建/链接
test.cc

如果您正确使用编译器,请尝试在
test.cc
文件的顶部包含
“test.h”

#include "test.h"

int test() {
   std::cout << "This is a test" << std::endl;
}

假设您正确使用了编译器,请尝试在
test.cc
文件的顶部包含
“test.h”

#include "test.h"

int test() {
   std::cout << "This is a test" << std::endl;
}
罪魁祸首来了

c++main.cc-o main

您需要链接test.o

c++main.cc test.cc-o main

罪魁祸首来了

c++main.cc-o main

您需要链接test.o

c++main.cc test.cc-o main


你得到的错误是什么?请发布它。我怀疑这是链接器问题,而不是编译器问题。你得到的错误是什么?include没有问题,只要
test.cc
被列为编译,但它不会编译。
std::cout
没有声明。你必须
\include
test.cc
中est.cc缺少一些#includes
c++main.cc-o main
只编译
main.cc
。您还需要将
test.cc
编译到
test.o
,然后将
test.o
main.o
链接到一个可执行文件中。您遇到了什么错误?请发布。我怀疑这是链接器的问题,不是编译器问题。您遇到了什么错误?include没有问题,只要
test.cc
被列为编译,但它不会编译。
std::cout
未声明。您必须
\include
test.cc
中。test.cc缺少一些#include
c++main.cc-o main
仅编译
main.cc
。您还需要将
test.cc
编译成
test.o
,然后将
test.o
main.o
链接到一个可执行文件中。感谢您的回答,我实际上没有意识到我的函数是错误的。问题是我遇到了链接器错误。@Francis您必须将这两个模块链接在一起,以便链接器将能够找到测试的定义。谢谢你的回答,我实际上没有意识到我的函数是错误的。问题是我得到了一个链接器错误。@Francis你必须将两个模块链接在一起,链接器才能找到测试的定义。我试过了,但它仍然给了我链接器错误。只是e我想说的是,你需要确保你是针对它链接的。我试过了,但它仍然给了我链接器错误。只是编辑说,你需要确保你是针对它链接的。