-1

Consider following two programs.

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";
}

I am compiling like following.

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

How can I solve this error? What I am doing wrong?

Destructor
  • 14,123
  • 11
  • 61
  • 126
  • You have to declare the class `test` (including its methods) in p2.cpp (usually, we declare it in a header file and include the header file in both sources files) – Caninonos Aug 04 '15 at 19:22

1 Answers1

1

Essentially, you need to:

  1. Create a new file test.h
  2. Move your struct test { ... }; into the file test.h
  3. Add `#include "test.h" to both of your source files.
  4. Recompile both files.

You may want to consider using a makefile to compile your files, and add a dependency on test.h to p1.cpp and p2.cpp, so that these get recompiled when you modify test.h

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227