Header Files with Source Files C++ - c++

I am trying to implement Header Files with Source Files using C++, but in the terminal the give me some errors.
Here is the code:
main.cpp
#include <iostream>
#include "add.h"
using namespace std;
int main()
{
cout << "The Sum of 3 and 4 is: " << add(3,4) << endl;
return 0;
}
add.cpp
int add(int x, int y)
{
return (x + y);
}
add.h
#ifndef ADD_H
#define ADD_H
int add(int x, int y);
#endif
Terminal Messages:

Try g++ -o add.o add.cpp followed by g++ -o HeaderTest main.cpp add.o.

Your code in C++ is perfectly fine.
What you need is probably some adjustments in building.
You should either read on how to build, i.e. compile and link manually or use some IDE, or at least build system like Make, CMake, QMake etc.
If you want to do this by hand please provide command you have used to build this sample.

You did use the C-compiler. The warning tells you that you provide C++-code to the C-compiler. In case you want to get rid of this warning, try clang++ -o add.o add.cpp followed by clang++ -o HeaderTest main.cpp add.o

Related

How to compile C++ program with a main, header and implementation file using command prompt, notepad and MinGW?

I am trying to learn C++ myself. I have installed minGW in my computer and to compile any .cpp file I use the command g++ -o main main.cpp in command prompt to compile and then I type main.exe to run it and it usually works. I use notepad to write .cpp files by the away. But when I tried to compile programs with separate header file (test.h for example) and implementation file ( test.cpp for example) it does not compile. I typed the code g++ main.cpp test.cpp in the command prompt but it showed me error. I am not sure if the code I typed in the command prompt is right but I found it on this pdf file. link to the pdf file
I typed exactly the 1st code given on the pdf file. For convenient the code is given below:
File: Num.h
class Num{
private:
int num;
public:
Num(int n);
int getNum();
};
File: Num.cpp
#include "Num.h"
Num::Num() : num(0) { }
Num::Num(int n): num(n) {}
int Num::getNum()
{
return num;
}
File: main.cpp
#include <iostream>
#include "Num.h"
using namespace std;
int main()
{
Num n(35);
cout << n.getNum() << endl;
return 0;
}
And to compile this from the command prompt I typed
g++ main.cpp Num.cpp
But the cmd shows the error massage "no declaration matches 'Num::Num()'".
As I am new to this I don't know what to do or what is wrong with this code. Any help is much appreciated.
You header doesn't include your zero arg constructor.
try
class Num{
private:
int num;
public:
Num(); //added this
Num(int n);
int getNum();
};

I cannot run multiple files within solution explorer Visual Studio Community 2015

I'm a beginner at C++ and I am willing to learn a lot more. I am using this website called learncpp.com and I've hit a few lessons, so far so good.
Unfortunately, I came to this part of the lesson: http://www.learncpp.com/cpp-tutorial/18-programs-with-multiple-files/ and my Visual Studio 2015 won't compile 2 files in the solution. The site says that it will be using this method a lot more in the future so I am concerned that I won't be able to proceed if I don't get this solved.
I have 2 files. One of which is named add.cpp and the other is named main.cpp.
The main.cpp contains the code:
#include "stdafx.h"
#include <iostream>
int add(int x, int y);
int main()
{
std::cout << "The sum of 3 and 4 is: " << add(3, 4) << std::endl;
return 0;
}
And my add.cpp contains
#include "stdafx.h"
int add(int x, int y)
{
return x + y;
}
When I run the program, I get this message:
Anybody know a fix? I really want to continue this fun journey into learning C++.
Are you getting compile errors for
#include "stdafx.h"
You may need to recreate the project or remove the includes for stdafx.h.
stdafx.h is used for precompiled headers. To use this feature, when creating the project, after clicking on next, click on check box for "precompiled headers" and do not click on check box for "empty project", and uncheck "secure development lifcycle (SDL)". Note that this will create stuff.cpp for the main source file. You can copy the source from main.cpp into stuff.cpp. You'll need to add "existing item" to include add.cpp into the project.
The alternative is to not use precompiled headers, and not use stdafx.h, which is a part of the precompiled headers. When creating a project, I normally clear "precompiled headers", clear "secure development lifcycle (SDL)", and set "empty project".
that is a sign of unsuccessful build and for sure as long as you didn't include add.h in fact I think you didn't even create add.h because I see Add() prototype in main.cpp which excludes decalring it in a header.
the solution:
1- create a header file Add.h which will look like:
// add.h
#ifndef ADD_H_
#define ADD_H_
int add(int x, int y);
#endif
2- file add.cpp:
// add.cpp
#include "add.h"
int add(int x, int y)
{
return x + y;
}
3- main.cpp:
// main.cpp
#include "stdafx.h"
#include "add.h"
#include <iostream>
// int add(int x, int y); // there's no need to re-declare it here because you already declared it in header
int main()
{
std::cout << "The sum of 3 and 4 is: " << add(3, 4) << std::endl;
return 0;
}
4- go to MSVC: project->add existing item then select add.cpp
5- now compile and build and run.
I wish it will work for you.

My first multi-file C++ Program Keeps Giving Me Error Messages

Add.cpp
int add(int x, int y)
{
return x + y;
}
Main.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
return 0;
}
When I try to compile this program I get an error message for line 6 of main.cpp that states: "error: 'add' was not declared in this scope".
Create a header file
Contents:
int add(int x, y);
Include that file main.cpp
i.e. #include "headerfile.h"
Then the rest is up to the compiler environment. Basically need to compile each .cpp to object code and then link them. You need to read up about this as this differs between environment. Also read up on header guards and also stuff like graadle, SCONS, Makefiles. Also good to learn about version control systes e.g. mercurial.
Guess you going to have a busy day
You need Add.h file and include it in your Main.cpp
Add.h
int add(int x, int y);
Main.cpp
#include <iostream>
#include "Add.h"
...
In c++ the scope is all visible functions/methods and variables. In order for it to be seen in the scope in this instance you would have to create a header file that contains your method "add". One way to do this would be to instead of having it in a .cpp file have it in a .h file, then include that .h file in your main.cpp file like this
#include "Add.h"

How to use header files?

I wanted to learn using header files. and I got an error. here is my code:
printmyname.h:
void printMyName();
printmyname.cpp:
#include "printmyname.h"
void printMyName() {
cout << "omer";
}
try.cpp (main file):
#include <iostream>
#include "printmyname.h"
using namespace std;
int main() {
printMyName();
return 0;
}
Here is the error:
undefined reference to `printMyName()`
What's is the problem?
Undefine reference has nothing to do with your header file in this case. It means the linker cannot find the implementation of printMyName which is in printmyname.cpp. If you are using g++, you should try:
g++ try.cpp printmyname.cpp -o yourBinaryName
If you are using a makefile, you should add dependency(printmyname.cpp) correctly for try.cpp.
Edit:
As #zmo suggest in his comment:
you can also do it through a two times compilation (more suitable with Makefiles):
g++ -c printmyname.cpp
g++ try.cpp printmyname.o -o yourBinaryName
If you are using Windows, you need to add the printmyname.cpp to your project too.
Consider adding an include guard to your header
#ifndef PRINTMYNAME_INCLUDED
#define PRINTMYNAME_INCLUDED
void printMyName();
#endif
You will also need to move the #include <iostream> and using namespace std; from the try.cpp to the printmyname.cpp file.
You need to add code/definition in printMyName.cpp inside printMyName.h only.
void printMyName();
{
cout << "omer";
}

I get an "undefined reference to ..." for two of my functions

I have created three separate files. The first is the main.cpp the 2nd is a header file called "statistics.h" which has the declarations for the two functions i am getting the error and the 3nd is a file called statistics.cpp which holds the implementation of the two functions.
Here is my main file:
#include <iostream>
#include "statistics.h"
using namespace std;
int main()
{
cout<<"This program provides the average and the standard deviation of 1,2,3 or 4 numbers."<< endl;
while(true){
start:
unsigned int howmany;
cout<<endl;
cout<<"How many numbers do u wish to receive as input?? ";
cin >> howmany;
if (howmany>4){
cout<<"You should pick at most 4 numbers u idiot!!!"<< endl<<endl;
goto start;
}
if(howmany==0){
return 0;
}
cout<< endl;
double nums[howmany];
for (int i=0;i<howmany;i++){
cout<<"Give me the number "<<i+1<<":";
cin>>nums[i];
}
double avg=average(nums,howmany); /////////////////////////////
double stdev=standard_deviation(nums,howmany,avg); ////////////////////
cout<< endl<<"Average: "<<avg<<". Standard Deviation: "<< stdev<< endl;
}
}
My header file is:
#ifndef STATISTICS_H_INCLUDED
#define STATISTICS_H_INCLUDED
double average(double ar[],int hm);
double standard_deviation(double ar[],int hm,double avrg);
#endif // STATISTICS_H_INCLUDED
And my implementation file statistics.cpp is:
#include<iostream>
#include"statistics.h"
#include <math.h>
using namespace std;
double average(double ar[],int hm){
double sum=0.0;
double average;
for(int i=0;i<hm;i++){
sum+=ar[i];
}
average=sum/hm;
return average;
}
double standard_deviation(double ar[],int hm,double avrg){
double std_dev;
double sum=0;
double ans;
for(int i=0;i<hm;i++){
sum+= ((ar[i]-avrg)*(ar[i]-avrg));
}
ans=sqrt(sum/hm);
return ans;
}
I am getting the errors in my main file (i have marked the corresponding lines with consecutive ////////). What could be wrong?? I am sure its something stupid from my part.
As i am using codeblocks i finally found the solution. I just needed to add #include "statistics.cpp" to my main.cpp file.
You forgot to link statistics.o together with main.o, so your hypothetical executable will not contain the function definitions.
(The hypothetical executable can thus not exist, so you're getting a linker error.)
Variation 1
Where you're writing something like:
g++ main.cpp -o myExecutable
instead write:
g++ main.cpp statistics.cpp -o myExecutable
Variation 2
Where you're writing something like:
g++ -c main.cpp
g++ main.o -o myExecutable
instead write:
g++ -c main.cpp
g++ -c statistics.cpp
g++ main.o statistics.o -o myExecutable
If you're still having trouble, try reversing the order in which you provide the filenames to g++ (though the above should be correct).
Incidentally, you are not allowed to define an array with variable dimensions. Use a std::vector instead.
As i am using codeblocks i finally found the solution. I just needed to add #include "statistics.cpp" to my main.cpp file.
!!! This is NOT a solution. Do not include implementation files. You will fall into a pit of despair, decay and disorganization.
Everything was fine with your use of header files. You just need to tell your IDE to compile both files as a single project. Consult the documentation.