1

I would like to use one function from Stats.cpp in Application.cpp. Here are my code snippets:

In Stats.h:

#ifndef STATS_H
#define STATS_H

class Stats
{
public:
    void generateStat(int i);
};

#endif

In Stats.cpp:

#include Stats.h
void generateStat(int i)
{
    //some process code here
}

In Application.cpp:

int main()
{
    generateStat(10);
}

I get an "unresolved external symbol" error however I don't know what I else I would need to include in order for Application.cpp. Any thoughts?

1
  • This is funny... The call generateStat(10) seems to be accepted by the compiler without any previous declaration. Is that C++? Commented Mar 26, 2014 at 20:16

3 Answers 3

2

In Stats.cpp

you need to define generateStat like following :

#include Stats.h
void Stats:: generateStat(int i) // Notice the syntax, use of :: operator
{
    //some process code here
}

Then create object of class Stats, use it to call the public member function generateStat

Stats s;
s.generateStat( 10 ) ;

Build the application using :

g++ -o stats Stats.cpp Application.cpp -I.

Sign up to request clarification or add additional context in comments.

Comments

0

generateStat is part of your Stats class. You need to instantiate a Stats object (along with the necessary includes for Stats.h in your main class)

For example,

Stats stat;
stat.generateStat(i);

Also, your function definition needs to include the class name Stats::generateStat.

Comments

0

The same error msg occured 2 weeks ago (at work).

At first glance --- Try:

 void Stats::generateStat(int i) {
     //some process code here }

The class name was missing. Hence, unresolved.

btw Concerning your header --- another issue, this #ifndef directive should not be necessary cause you should declare Stats only once in a namespace.

#ifndef CLASS_H
#define CLASS_H
#include "Class.h"
#endif

This is a generic example - Usable in cpp files.

EDIT: Now, I saw your invocation (main method in your case). You need an object instance to invoke your method.

Stats* stats = new Stats(); //add a default constructor if not done
stats->generateStat(77);

// any other stats stuff ......
// in posterior to the last use
delete(stats);

In your header:

Stats::Stats(){}; //with an empty body - no need to write it again in the cpp file

4 Comments

You have a few issues with this code, better check it over.
@codah what are u talking about?
Firstly Stats stats should be Stats* stats. And then you would have to change stats.generateStat to stats->generateStat. Why not just create it on the stack anyway? And you didn't delete it (might as well show that if you're going to advocate creating on the heap).
@codah +1 && yes, did not focus on that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.