如何在单独的源文件中定义成员函数?

时间:2015-08-04 17:02:05

标签: c++ function definition compilation

考虑以下两个程序。

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.

如何解决此错误?我做错了什么?

1 个答案:

答案 0 :(得分:1)

基本上,您需要:

  1. 创建一个新文件test.h
  2. test.h移至文件test.h
  3. 添加`#include&#34; test.h&#34;两个源文件。
  4. 重新编译这两个文件。
  5. 您可能需要考虑使用makefile来编译文件,并将-10的依赖项添加到p1.cpp和p2.cpp,以便在修改test.h时重新编译这些文件。