It is unclear whether the comments solved your problem. In separating your source into a header and multiple sources, your primary problem evidenced by the error is that you include an incomplete constructor for class Greeter
in Greeter.h
. Specifically, you fail to include "an empty parameter list" to complete the constructor, e.g.
Greeter() {}; /* default construct */
See cppreference - Default constructors
The next issue you should avoid is including using namespace std;
in the header file. See “using namespace” in c++ headers. Instead, simply make your call to cout
, std::cout
and eliminate the need to include the namespace altogether.
Next, while iostream
has proper header guards, you only need to include it in Greeter.cpp
(that is the only source making use of an iostream
function). You should also include header guards in your Greeter.h
to prevent multiple inclusions during compilation. Simply create a #define
and check whether or not that is already defined within the header, e.g.
greeter.h
#ifndef my_class_greeter_h
#define my_class_greeter_h 1
class Greeter {
public:
Greeter() {}; /* default construct */
void greet();
};
#endif
Now every file that includes greeter.h
will avoid including it again if my_class_greeter_h
is already defined.
greeter.cpp
Your source file with your class function definition is the only source that relies on an iostream
call, and is the only file that requires #include <iostream>
, e.g.
#include <iostream>
#include "greeter.h"
void Greeter::greet(){
std::cout << "Hello World!\n";
}
main.cpp
You main.cpp
source file need only include your header containing the class definition, e.g.
#include "greeter.h"
int main (void) {
Greeter greeter; /* instantiate greeter */
greeter.greet(); /* call greet() */
return 0;
}
Both Sources Must Be Compiled
Compiling the separate source files requires that both main.cpp
and greeter.cpp
be compiled (either compiling greeter.cpp
to object or by simply including both .cpp
files in your compile string).
Compiling With gcc/clang
$ g++ -Wall -Wextra -pedantic -std=c++11 -Ofast -o main main.cpp greeter.cpp
Compiling With VS (cl.exe
)
> cl /nologo /W3 /Ox /EHsc /Femain /TP main.cpp greeter.cpp
(do not accept code until it compiles without warning)
Example Use/Output
In either case, the output is as expected:
$ ./main
Hello World!
Look things over and let me know if you have further questions.