【问题标题】:How to define member function in separate source file? [duplicate]如何在单独的源文件中定义成员函数? [复制]
【发布时间】:2015-08-04 17:02:04
【问题描述】:

考虑以下两个程序。

p1.cpp

#include <iostream>
struct test
{
    void fun();
};
int main()
{
    test t;
    t.fun();
}

p2.cpp

#include <iostream>
void test::fun()
{
    std::cout<<"fun() is called\n";
}

我正在编译如下。

g++ -c -o p1.o p1.cpp
g++ -c -o p2.o p2.cpp   <--------- This gives me compiler error.

我该如何解决这个错误?我做错了什么?

【问题讨论】:

  • 你必须在p2.cpp中声明类test(包括它的方法)(通常,我们在头文件中声明它,并在两个源文件中都包含头文件)

标签: c++ function definition compilation


【解决方案1】:

基本上,您需要:

  1. 新建文件test.h
  2. struct test { ... }; 移动到文件 test.h 中
  3. 将 `#include "test.h" 添加到您的两个源文件中。
  4. 重新编译这两个文件。

您可能需要考虑使用 makefile 来编译您的文件,并将对 test.h 的依赖添加到 p1.cpp 和 p2.cpp,以便在您修改 test.h 时重新编译这些文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多