Using multiple .cpp files in c++ program? - c++

I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.
Let me explain better if you wouldn't understand:
I have one file: main.cpp inside it I have main function.
I have the second file: second.cpp inside I have a function called second() I want to call this function called second() from my main function..
Any help?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.
other.h
void MyFunc();
main.cpp
#include "other.h"
int main() {
MyFunc();
}
other.cpp
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}

In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.
In second.h you just declare like this void yourFunction();
In second.cpp you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h" also in the beginning of second.cpp
Hope this helps:)

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

Related

Trouble with the headers of various c++ class in separate files

I have 5 files, a main file and two classes with its two headers files like that:
file main.cpp:
#include "parent.hpp"
#include <iostream>
int main (){
Parent parentInstance;
parentInstance.function();
return 0;
}
file parent.hpp:
class Parent {
public:
void function();
};
file parent.cpp:
#include "child1.hpp"
void Parent::function() {
Child1 Child1Instance;
Child1Instance.speak();
}
file child1.hpp:
#include "parent.hpp"
#include <iostream>
class Child1 : public Parent {
public:
void speak();
};
file child1.cpp:
#include "child1.hpp"
void Child1::speak () {
std::cout << "Hi, I'm child1" << '\n';
}
It compile and works without any problem, -although it may have been done with bad practices-. The problem rises when I try to add a new class with its own cpp and hpp files, called Child2 that its basically the same code than Child1, but I don't know how organize properly the headers for make this code works:
void Parent::function() {
Child1 Child1Instance;
Child2 Child2Instance;
Child1Instance.speak();
Child2Instance.speak();
}
and return me:
Hi, I'm child1
Hi, I'm child2
Some rules:
A header file always has include guards (or #pragma once).
Every .cpp includes its corresponding .hpp as its first (non-comment) line.
Only include into a .cpp what you explicitly use in that .cpp.
This should solve most of your problems.
Some explanations:
Without the guards, you can end up including the same file twice transitively, say you include a.h and b.h, but b.h already includes a.h... This causes some confusing redefinition errors.
You must include the header so that function definitions in the .cpp correspond to the declarations in the .hpp. Having it on the very first line is just good practice.
Including exactly what you use avoids confusing errors if you forgot an #include somewhere else.
I'm very grateful for the comments, all my knowledge is self-taught...now the problem is easily solved:
main.cpp has no change.
file parent.hpp:
#ifndef _PARENT_HPP_
#define _PARENT_HPP_
class Parent {
public:
void function();
};
#endif /* _PARENT_HPP_ */
file parent.cpp:
#include "parent.hpp"
#include "child1.hpp"
#include "child2.hpp"
void Parent::function() {
Child1 Child1Instance;
Child2 Child2Instance;
Child1Instance.speak();
Child2Instance.speak();
}
file child1.hpp and child2.hpp (change 1 to 2):
#include "parent.hpp"
#include <iostream>
class Child1 : public Parent {
public:
void speak();
};
file child1.cpp and child2.cpp (change 1 to 2):
#include "child1.hpp"
void Child1::speak () {
std::cout << "Hi, I'm child1" << '\n';
}
And the result:
Hi, I'm child1
Hi, I'm child2
It works. However, I'd like to hear if there's anything that could be improved or a mistake that could be corrected.

C++ Namespace Declaration and Definition

Folks,
I crated a name space in a single file, but how exactly do I separate the definition and declaration?
Can I create a .h for declaration and a .cpp for definition just like in a class set of file? If yes, then, do I need to include the namespace header file in my new program, or is the using namspace mynamespace enough?
Any decent C++ book should cover namespaces and code separation.
Try something like this:
myfile.h
#ifndef myfile_H
#define myfile_H
namespace myns
{
class myclass
{
public:
void doSomething();
};
}
#endif
myfile.cpp:
#include "myfile.h"
void myns::myclass::doSomething()
{
//...
}
And then you can use it like this:
#include "myfile.h"
myns::myclass c;
c.doSomething();
Or:
#include "myfile.h"
using namespace myns;
myclass c;
c.doSomething();

Methods in new cpp files? [duplicate]

I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.
Let me explain better if you wouldn't understand:
I have one file: main.cpp inside it I have main function.
I have the second file: second.cpp inside I have a function called second() I want to call this function called second() from my main function..
Any help?
You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.
other.h
void MyFunc();
main.cpp
#include "other.h"
int main() {
MyFunc();
}
other.cpp
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.
In second.h you just declare like this void yourFunction();
In second.cpp you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h" also in the beginning of second.cpp
Hope this helps:)
You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

C++ How to call a function from another file with the same name as a function in another file when both are included?

I am wondering how I could call a function from another file with the same name as a function in another file when both are included.
Example:
main.cpp
#include "a.h"
#include "b.h"
using namespace std;
int main()
{
start();
return 0;
}
a.h
#ifndef _A_H
#define _A_H
#pragma once
int start();
#endif
a.cpp
#include "stdafx.h"
using namespace std;
int start()
{
//code here
return 0;
}
b.h
#ifndef _B_H
#define _Win32_H
#pragma once
int start();
#endif
b.cpp
#include "stdafx.h"
using namespace std;
int start()
{
//code here
return 0;
}
the start(); in main.cpp will use start(); from a.h but I want it to use start(); from b.h
How do I do to select start(); in b.h?
Assuming that the functions are defined in the respective .cpp files, i.e., one is defined in a.cpp and one in b.cpp, then this cannot happen. Once you try to link your code, you will get the error that start() is defined twice. Therefore, you do not have to reason about how to call one of them; the code will not link anyway unless the two functions are the same (i.e. defined in the same cpp file). If this is the case, then it doesn't matter which one is called (as there is only one).

Multiple definition of a function error, even when using #if guard clauses

I am creating a simple UTIL.h file contain aplusb(int, int) function for my C++ project. However I cannot compile and the error message is about multiple definition of `aplusb(int, int)'. Would you please help me correct the error or give me some hints?
I attach here my project for your detail reference.
File UTIL.h
#ifndef UTIL_H_
#define UTIL_H_
int aplusb(int a, int b) {
return a + b;
}
#endif /* UTIL_H_ */
File ClassA.h
#ifndef CLASSA_H_
#define CLASSA_H_
class ClassA {
public:
ClassA();
virtual ~ClassA();
private:
int sum;
};
#endif /* CLASSA_H_ */
File ClassA.cpp
#include "ClassA.h"
#include "UTIL.h"
ClassA::ClassA() {
// TODO Auto-generated constructor stub
sum = aplusb(3,5);
}
ClassA::~ClassA() {
// TODO Auto-generated destructor stub
}
File ClassB.h
#ifndef CLASSB_H_
#define CLASSB_H_
class ClassB {
public:
ClassB();
virtual ~ClassB();
private:
int sum;
};
#endif /* CLASSB_H_ */
File ClassB.cpp
#include "ClassB.h"
#include "UTIL.h"
ClassB::ClassB() {
// TODO Auto-generated constructor stub
sum = aplusb(5,6);
}
ClassB::~ClassB() {
// TODO Auto-generated destructor stub
}
Compile error message
ClassB.o: In function `aplusb(int, int)':
/home/vtvan/Desktop/workspace/commonfunc/UTIL.h:11: multiple definition of `aplusb(int, int)'
ClassA.o:/home/vtvan/Desktop/workspace/commonfunc/UTIL.h:11: first defined here
collect2: error: ld returned 1 exit status
make: *** [commonfunc] Error 1
First variant - use inline specifier
#ifndef UTIL_H_
#define UTIL_H_
inline int aplusb(int a, int b) {
return a + b;
}
#endif /* UTIL_H_ */
Second variant - write definition in .cpp file.
You created the function aplusb in your include file. This means that for every file you include it to, a public function aplusb will be created, resulting in a name clash.
If the function should be inline, then mark it so. If the function should be a template, then mark it so. If the function should be as you wrote it, put it in a cpp file and just keep the protoype in the h file.
.h
#ifndef UTIL_H_
#define UTIL_H_
int aplusb(int a, int b);
#endif
.cpp
int aplusb(int a, int b)
{
return a+b;
}
You should declare your aplusb function in the header file, and provide the definition in a cpp file. Something like
util.h:
#ifndef UTIL_H_
#define UTIL_H_
int aplusb(int, int);
#endif /* UTIL_H_ */
The error message is telling you that each time that you include the util.h file, you are re-defining the function, which is exactly what you are doing :-) This is a violation of the ODR (one-definition-rule), which states that the definition (of a function, in this case) must be unique. Otherwise the compiler would be unable to choose between the alternatives (even if, like in this case, they happen to be equal).
Note that templates complicate the matter a bit (in short, because a template is not a definition until instatiated).
Header files are not intended to have actual functions in them (certain C++ aspects such as templates not withstanding). General practice in your case would have you changing your UTIL.H to just prototyping the function (int aplusb(int a, int b);) and moving its implementation to a source file.
You could also make a Util struct where every function is declared static. You can then access every function using Util::<function name>
File UTIL.h
#ifndef UTIL_H_
#define UTIL_H_
struct Util{
static int aplusb(int a, int b) {
return a + b;
}
};
#endif /* UTIL_H_ */
File ClassA.cpp
#include "ClassA.h"
#include "UTIL.h"
ClassA::ClassA() {
sum = Util::aplusb(3,5);
}
ClassA::~ClassA() {
}
File ClassB.cpp
#include "ClassB.h"
#include "UTIL.h"
ClassB::ClassB() {
sum = Util::aplusb(5,6);
}
ClassB::~ClassB() {
}