Hi, i'm new in this forum and i have some questions in C++...

1. I have main.cpp, which has int main()... I also have some.cpp which has int some(). How do i access/use some() from main() ?

2. Also, how can i use some other (I'm not sure i'm saying it correctly) "Functions" in one file ? I don't really understand that.

Please Help !

As well as some.cpp, you also have some.h

Which has say
extern int some();

Main.cpp then has
#include "some.h"

And you compile main.cpp and some.cpp together.

Usually since Salem started to programming so long ago, he may not be so clear to new programmers like us. You, use the extern keyword for the declarations of variables if they are defined in another file. Note that there are two things about variables; declarations and definitions. Another thing that Salem didnt bother to say is since the compiler compiles your code from top to bottom, you have to put the declarations on top of your files, which is why you put them into header files and then include those headers before adding any other code to your files.
For example, if you have a function definition below the main function, and if you call them from within the main function, your code wont compile generating error that it couldnt find the function.
However, you dont need to have headers to use those extern variables(variables that are defined in another file), you can still use extern keyword before their declarations and just use them.

No need in extern keyword for external function declarations. Use function prototypes to declare function interface:

int some(); // No function body: it's a function declaration.
... // Now compiler knows that some is a function name.
int some() {
... // That's a function definition.

You must provide an entity name declaration textually before use it - that's all.

Thank you, everyone !

But... I still can't understand something : How can i call a method from another file ? Is it like this :


#include <iostream>
#include <some.h>

using namespace std;

int main()
cout << "Some Stupid Main Method" << endl;

#include <some.h>
#include <iostream>

using namespace std;

int some()
cout << "Another Stupid Method" << endl;

#include <iostream>

extern void some();

At the command line, it would be

g++ main.cpp some.cpp

If you're using an IDE which has the idea of a "project", then you would add main.cpp and some.cpp to the source files list in the project settings.

Your code as you posted it is basically correct.

The include for some should be #include "some.h" the version you used will not search the current directory the quote version will search there first.

The function prototype in some.h should match the function signature. Your some.h has void some() but your some.cpp has int some()

This article has been dead for over six months. Start a new discussion instead.