-4

I am using the C++ MinGW compiler and I'm trying to figure out how to use methods and create methods. This is what I tried:

#include <iostream>
using namespace std;

int main()
{
        test();
}

void test()
{
        cout << "Hello" << endl;
}

I am a beginner at c++ but I know a lot about Java. Here's the compiler message:

12:09:06 **** Incremental Build of configuration Debug for project String Gen ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.cpp" 
..\main.cpp: In function 'int main()':
..\main.cpp:6:14: error: 'test' was not declared in this scope

12:09:06 Build Finished (took 411ms)
kzolp67
  • 193
  • 1
  • 2
  • 12
  • 1
    Go through this http://www.cplusplus.com/doc/tutorial/functions/ – Jayram Jul 10 '13 at 03:52
  • 2
    Please, for future questions, also include any compiler warnings/errors that you encounter, and explain *why* things aren't working. Don't make us guess as to what problems you're encountering. Luckily this was an obvious one. – Jonathon Reinhart Jul 10 '13 at 03:58
  • Yes I thought it was obvious and that's why I didn't put the compiler error in. – kzolp67 Jul 10 '13 at 04:00
  • 2
    You might and it might be, but three months from now, someone might come across this question and wonder what the problem was - don't forget these questions should remain for some time to come... – icedwater Jul 10 '13 at 04:02
  • Ok I will try and remember for future posts – kzolp67 Jul 10 '13 at 04:04
  • 2
    In C++, methods are called "member functions". – Dietrich Epp Jul 10 '13 at 04:05
  • 2
    Well, and since these aren't member functions, they're referred to as free functions. Global function, or just function, could also work. – chris Jul 10 '13 at 04:09
  • I have added the compiler message – kzolp67 Jul 10 '13 at 04:14

2 Answers2

4

test() must be declared before main().

#include <iostream>
using namespace std;

void test()
{
        cout << "Hello" << endl;
}

int main()
{
        test();
}

Or you can use a forward declaration:

#include <iostream>
using namespace std;

void test();

int main()
{
        test();
}

void test()
{
        cout << "Hello" << endl;
}

The order in which things are declared doesn't matter in languages like Java and C#, but for the C and C++ compilers, the order does matter. Basically, in your example, the compiler will get to test(); and say "I don't know what test is." So either you define the whole test() function before main(), or you simply declare it ahead of time to tell the compiler "hey, there's a function named test with this signature somewhere in my program."


A more complex example:

test.h

void test();

test.cpp

void test() {
    // Whatever...
}

main.cpp

#include "test.h"

int main() {
    test();
    return 0;
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • How would I go about calling a method in another .cpp file – kzolp67 Jul 10 '13 at 03:59
  • 2
    There are plenty of tutorials out there about this, you should really look at them. But basically, every `.c` or `.cpp` file that "exports" a function (to be used by other files) should have those functions *declared* in a `.h` header file. This `.h` file is included by the files that want to call those functions. – Jonathon Reinhart Jul 10 '13 at 04:00
  • Sorry I'm a beginner I don't know much at all about c++ can you please explain further – kzolp67 Jul 10 '13 at 04:02
  • 1
    I just edited my answer to include an example. It's very straightforward. Also, StackOverflow is not a place to teach you how to program. Again, there are hundreds or thousands of examples out there. A Google search for ["how to use header files"](http://www.google.com/search?q=how+to+use+header+files) led me to [Header files](http://www.learncpp.com/cpp-tutorial/19-header-files/). – Jonathon Reinhart Jul 10 '13 at 04:05
  • 1
    @kzolp67, That's definitely explained in any [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). If you're reading one, try looking ahead if you have questions like this. If not, they're one of the best ways to learn. There are books suited to those who come with programming experience. – chris Jul 10 '13 at 04:06
  • Yeah unfortunately I don't have any c++ books but I do have a c book but it still doesn't have it. – kzolp67 Jul 10 '13 at 04:08
  • Your C book will most certainly explain how to use multiple compilation units (`.c` files) and accompanying header files. – Jonathon Reinhart Jul 10 '13 at 04:09
  • 1
    @kzolp67, I warn you now not to use the C book to learn C++ (not that I'm assuming you are, just warning not to). You'll end up with C code disguised as C++, which is something that a lot of people hate dealing with. C++ has so many utilities layered on that ease a lot of operations. For example, `std::string`, `std::vector`, OOP (well, C has that, but it's a lot less structured). – chris Jul 10 '13 at 04:10
  • Yeah, I get a lot of the object orientated stuff mixed up – kzolp67 Jul 10 '13 at 04:15
1

The C++ build model is quite different from the Java model. In C++ there are 'declarations' and 'definitions' of various entities, such as functions, classes, methods, etc. C++ source consists of a series of declarations and definitions. Individual modules, or "translation units" are compiled into object code containing whatever entities are defined in that translation unit. Then the compiled translation units making up a program are 'linked' together, where entities defined in one translation unit get hooked up to their usages in other translation units.

In a translation unit, certain uses of entities require only a declaration, while others require full definitions. For example, calling a function only requires the function to be declared. Creating a variable that is a pointer to an object only requires the object's type to be declared. Creating a variable who's type is a class type (rather than a pointer) requires the full definition of the class. What requires a full definition and what only requires a declaration depends on what is required in order to implement the usage. In particular if the usage only needs to know interface details then declarations are enough, but if implementation details are needed then the definition is required.

Additionally, C++ is specified such that the compiler can pretty much be single pass; declarations and definitions must appear in the source code before they are used (for the most part; there are some exceptions) so that C++ will already know what entity is being used when it is mentioned.


So the problem with your code is that when the compiler gets to test() it doesn't know what test is. It could be a type or a function or a variable. It doesn't know because it hasn't already been told. You need to tell it, by declaring test beforehand.

void test();

int main() {
  test();
}

Now the compiler will know that test is a function by the time it reaches the attempt to call it. And since calling a function doesn't need to know anything except the function's signature, you could put the definition of test into a completely different translation unit, if you wanted to. You'd compile both translation units and then the linker would connect the code that calls test() up to the definition of that function in the other compiled translation unit.


Header files are a common trick in C and C++ that make it easy to have a single source for declarations shared between translations units. They aren't strictly necessary, but if you mess up a declaration by declaring something slightly differently in different files then your program could fail in unexpected and unpredictable ways.

#include directives simply take whatever file you name and paste the contents into your source code. This way you have a single source for whatever it is you put in the header, such as a function declaration, for example. That way you can ensure that the an identical declaration is included in every file you need it in, without worrying about if maybe you declared something slightly differently in one file from another.

You can also put your class definitions in header files, because a class definition needs to be repeated in every translation unit where that class is used in certain ways. Again, you could write out the needed information manually in every translation unit, but it's easier to stick the definition in a header and let #include directives do the copying and pasting for you.


If you want to learn C++ I recommend getting a good book. If you weren't already familiar with programming I'd recommend Programming: Principles and Practice Using C++. Since you say you've already programmed then I've heard a better book for you might be Accelerated C++.

bames53
  • 86,085
  • 15
  • 179
  • 244