I have been searching online for solutions to this rather simple problem. My goal is to call a function from a separate .cpp file in my main.cpp file. What I have found thus far has told me to define my function in a separate .cpp file (averageScore.cpp) which looks like:
void averageScore()
{
"Blah, Blah, Blah"
}
And then declare the function as a prototype in a header file (Lesson1.h) which looks like:
#include "C:/averagescore.cpp"
void averageScore();
And finally call the function again in the main.cpp:
#include "Lesson1.h"
int main()
{
averageScore();
return 0;
}
I am currently a CS student and my overall objective with this method of organization and execution is to create a single project for all of the rudimentary programs we must create on a weekly basis instead of creating a new project for every single program. For reference, I am using VScode and have used the following link to help me thus far:
http://www.cplusplus.com/forum/beginner/97779/
My condolences and gratitude are extended to anyone who has taken the time to read through this and help me out!
To achieve what you want, you must create a header file, and declare your function there, for example:
lesson1.h
void averageScore();
In a .cpp file, you define that function and include the header you just created:
lesson1.cpp
#include "lesson1.h"
void averageScore(){
// Do what you want in this function
}
Then you can call that function in your main.cpp by including "lesson1.h":
main.cpp
#include "lesson1.h"
int main()
{
averageScore();
return 0;
}
Related
I just feel weird about how does that work ?
That my first time that I've ever seen that , two c++ files located in the same directory "Test1.cpp,Test2.cpp"
Test1.cpp :
#include <iostream>
void magic();
int main(){
magic();
return 0;
}
Test2.cpp :
#include <iostream>
using namespace std;
void magic(){
cout << "That's not a magic , it's a logical thing.." << endl;
}
As I mentioned above , they are in the same directory , with prototype of 'magic' function.
Now my question is , how does magic work without any inclusion of Test2.cpp ?
Does C++ include it by default ? if that's true , then why do we need to include our classes ? why do we need header file while cpp file can does its purpose ?
In order to obtain an executable from a C++ source code two main phases are required:
compilation phase;
linking phase.
The first one searches only for the signature of the functions and check if the function call is compatible with the found declarations.
The second one searches the implementation of the function among the libraries or objects linked through the options specified through command line of the linker (some compilers can automatically run the linker adding some command line options).
So you need to understand the compiler and linker options in order to understand this process.
The main catch of headers file is simplifying writing of code.
Let's think about next example:
test2.cpp
#include <iostream>
using namespace std;
void my ()
{ magic(); } // here we don't know what magic() is and compiler will complain
void magic(){
cout << "That's not a magic , it's a logical thing.." << endl;
}
This code gives next error:
gaal#linux-t420:~/Downloads> g++ test2.cpp
test2.cpp: In function ‘void my()’:
test2.cpp:6:9: error: ‘magic’ was not declared in this scope
{ magic(); } // here we don't know what magic() is and compiler will complain
^
To avoid this error we need to place declaration of magic() function before definition of my(). So it is good idea to place ALL declarations in one place. Header file is a such place. If we don't use headers, we'll need to paste declaration of magic() function in any cpp-file where it will be used.
Im just curious, but is there a way to make it so you don't have to put a class name before a function? here's an example:
HelloWorld.h
class HelloWorld{
HellowWorld();
};
HelloWorld.cpp
#include "HellowWorld.h"
HelloWorld::HelloWorld(){}
I'm wondering if there is a way to be able to have the .cpp file look like the following.
HelloWorld.cpp < New Version
#include "HellowWorld.h"
HelloWorld(){}
Functions do not have to be defined in the class, only declared.
I prefer to define the method contents in a separate file. This reduces the chance of other files compiling because I made a change to the content of a function.
Hello.hpp:
class HelloWorld
{
HelloWorld(); // Declares the constructor
};
Hello.cpp:
#include "Hello.hpp"
#include <stdio>
HelloWorld ::
HelloWorld()
{
std::cout << "Hello World\n";
}
Now I can make a change to the HelloWorld constructor and not worry about changing the header file. Because if the header file changes, all the source files that include Hello.hpp will need to be recompiled.
Edit 1: Reducing "HelloWorld::"
You can remove the HelloWorld:: part by incorporating a using statement:
#include "Hello.hpp"
#include <stdio>
using HelloWorld;
HelloWorld()
{
std::cout << "Hello Mars\n";
}
If this is a class member method then no, there is no way (apart from impractical showcase-only magic like don't put ; in .h but finish class definition in .cpp) to avoid class specification.
So I am working on my first multiple file, non-toy, c++ project. I have a class that represents a multi-spectral image and all the information that goes along with it.
My problem is how to design the part of the program that loads and object of this class with a file from disk!
I don't think I need a class for this. Would switching to a functional approach be better for the file loading. This way I can have just a source file (.cpp) that has functions I can call while passing in pointers to the relevant objects that will be updated by the file accessed by the function.
I don't think static functions are what I want to use? As I understand it they(static functions) are for accessing static variables within a class, aren't they?
If I go the functional route, from main(), how do I access these functions? I assume I would include the functions .cpp file at the beginning of the main() containing file. From there how do I call the functions. Do i just use the function name or do I have to pre-pend something similar to what you have to pre-pend when including a class and then calling its methods.
Here is some example code of what I have tried and the errors I get.
OpenMultiSpec.cpp
#include <iostream>
void test(){
std::cout << "Test function accessed successfully" << std::endl;
}
main.cpp
int main(){
test();
return 1;
}
The error says " 'test' was not declared in this scope "
OpenMultiSpec.h
void test();
main.cpp
#include "OpenMultiSpec.h"
int main(){
test();
return 1;
}
If they're in two separate files, and in your case, one being a header, use
#include "OpenMultiSpec.h"
If you decide to only use one file (as your comment says above), you won't need #include for your header file. Just place your function declaration anywhere before you call it.
#include <iostream>
void test() {
std::cout << "Test function accessed successfully" << std::endl;
}
int main() {
test();
return 1;
}
Main idea:
I wrote a piece of code for dijkstra's algorithm and I'm dandy. However, I need to call the function (from a header file) in other codes and stuff. But I need to store the variables only when the function is called (so once the function is called it will return variables but won't return variable from previous calls). And I need to reference these variables other codes/files.
How I'm storing variables:
a structure that contains two vector.
My question:
Would it be best to create a .h file to store a structure and just change the variables there or is there a way to call variable from another function in another file and use it without having to worry about memory issues and whatnot?
Also... how would I set up my .h file for this dijkstra algorithm if my my int main takes no arguments?......
-Edit-
typedef struct
{
int a;
int b;
} STR;
STR Func()
{
STR str;
str.a = 5;
str.b = 6;
return str;
}
Basic model of my code. But I need to reference the structure and it's variable in another file with another function. However I get undefined reference to 'main' error when compiling so I added an int main() that calls Func(). Suggestions?
-edit dos-
Proposed fix
.h should include:
struct_name dijkstra(input variables)
.cpp should include:
#include "dijkstra.h"
typedef struct{
blah...
}struct_name;
struct_name dijkstra{
struct_name retval;
function def...
return retval;
}
main.cpp should include:
#include "dijkstra.h"
#include "dijkstra.cpp"
int main(){
initialize variables... blah
struct_name return_struct = dijkstra(input variables);
return 0;
}
Usually you would pass in all the input data the algorithm needs as input parameters, and return all the useful output data the algorithm creats as a return type. You could create a separate C++ struct or class if you need to bundle a few pieces of information together.
For data structures used internally by the algorithm - you would usually declare them only in the .cpp file, not the .h file. So, the user will not have any access / visibility of the internals (which is useful if you want to change how it works later).
So, the header file should just have the function declaration - with input arguments and output return type. All the algorithm code goes into the .cpp file, which includes the .h file. The header file is the 'interface' and the cpp file is the 'implementation', which we try to keep separate.
EDIT : (summarizing useful points from subsequent discussion)
This tutorial shows how the 2 .cpp files and one .h file fit together. Basically both .cpp files include the .h file. The .h file includes the declarations (for both the function type and for the struct type) but not the function definition :
www.learncpp.com/cpp-tutorial/19-header-files/
Since you are using g++, you can compile them into a single executable using :
g++ -o executable_name main.cpp dijkstra.cpp
I've got 3 files that relate to this problem. file.h, file.C and user.C.
file.h has a private member, fstream logs.
In file.C's constructor it opens logs. It doesn't do this in the constructor, but the constructor calls a function OpenLog().
file.h also has an inline close function:
CloseLog() {if (logs) logs.close();}
The file user.C has an exit function which creates an instance of file, then calls CloseLog. It seg faults at this point. I created some other dummy tests, and it appears as though logs is lost in the mix somewhere ...
Going from file.C to user.C and then back to file.C causes this. If I have fstream logs as a global in file.C then it works - but I'd rather avoid a global.
Any thoughts on what I should do here? Please let me know if I should post more code about this, I can set up some dummy stuff to demo this better.
** Here's more code, as requested - I can't copy and paste, so forgive the lack of it please **
I will call the classes helpME.h, helpME.C and user.C
//helpME.h
#ifndef _helpME_H
#define _helpME_H
#include < iostream>
#include < fstream>
//various includes
class helpME {
private:
fstream logs;
public:
void CloseLog() {if (logs) logs.close();}
};
#endif
//end helpME.h
//helpME.C
void helpME::helpME(int argc, char** argv)
{
//various code
OpenLog();
}
void helpME::OpenLog()
{
//logname is set above, i had a print statement before that showed this is correct
logs.open(logname, ios::in | ios::out | ios::trunc);
}
//end helpME.C
//user.C
void user::quitHelpME(item)
{
helpME* hME = (helpME*) item;
hME->CloseLog();
}
//end user.C
Again - please forgive the lack of clarity, I'm thinking I may have just confused things more by adding this ... this code is on another box and can't be copied over.
void user::quitHelpME(item)
{
helpME* hME = (helpME*) item;
This doesn't create an instance, it's using C style casting to cast from whatever item is to a pointer to helpME.
if item is NULL then calling a method on it will seq fault.
otherwise still not enough detail in your example to give you an answer, the code present seems sound.
Because you've declared your variable in the .h file, you have two copies of it. The compiler doesn't 'see' .h files, it just copies/pastes what is in the file into the .C files, so, that's why you have two copies of the variable.
Declare the variable as extern in the .h file, and declare it again without the extern in only one .C file and don't use static in any declaration of that file.. It should fix your problem.