I have a simple cpp project that has one .cpp file(a.cpp) and two .h files (h1.h and h2.h).
In a.cpp, I have :
#include "h2.h"
#include "h1.h"
In h1.h, I have :
double abc = fun1(a, b); //using fun1() here. a and b are string types.
In h2.h, I have :
double fun1(string a, string b)
{ //definition
}
Error: in h1.h => fun1() in not declared in this scope.
Query is, m I doing this right? can one put function definition in a header file? should I use inline here?
Edit:
here is the h1.h
void checkForOneToOneSimilarity(vector <string> & folder1, vector <string> & folder2)
{
int i=0, j=0, l1 = folder1.size(), l2 = folder2.size();
//chunking(folder1[0]);
while(i < l1 && j < l2)
{
if(folder1[i] == folder2[j])
{
double similarity = fun1(folder1[i], folder2[j]);
i++;
j++;
}
else if(folder1[i] > folder2[j]) j++;
else i++;
}
}
You have declared double fun1() in h2.h,
but you called the function double fun1(std::string, std::string).
The compiler searches the definition double fun1(std::string, std::string) which is not declared.
You should change the function header in h2.h to double fun1(string a,string b)
you declared fun1() in h2.h and called the function h1.h so when the compiler search about fun1() it will not found it
try to include"h2.h" in the "h1.h" file
You can place function definitions in header files.
but here two things are wrong
You are calling fun1 inside h1.h , but it defined in h2.h. so h1.h cannot see the definition in h2.h.
for overcome this include h2.h to h1.h
Your function call and definition miss match.
function definition should be
double fun1(string a, string b)
{ //definition
}
matching function call should be
double abc = fun1("some string 1", "some string 2");
Append:
correct three files should be
h1.h
double addTwoStringNumbers (string a, string b)
{
double tot = atof(a.c_str()) + atof(b.c_str());
return tot;
}
h2.h
#include "h1.h"
void showValue()
{
double total = addTwoStringNumbers("2", "3");
std::cout << total << std::endl;
}
a.cpp
#include "h2.h"
int main()
{
showValue();
return 0;
}
Related
I have declared two constant functions in a header file that pop an error when I try to define them in an implementation file.
I noticed that removing "const" from the declaration gets rid of the errors but it is required by the professor that the methods are constant in the header file.
//header file
#ifndef DEGREE_RVC_H
#define DEGREE_RVC_H
#include <iostream>
using namespace std;
class degree {
public:
degree();
degree(double);
degree(double, char);
void setAll(double, char);
void setTemp(double);
void setScale(char);
double getF() const;
double getC() const;
private:
double temp;
char scale;
};
#endif
//implementation file
double degree::getC()
{
if (scale == 'c') {
return temp;
}
else return 5.0 / 9.0 * (temp - 32);
}
double degree ::getF()
{
if (scale == 'f') {
return temp;
}
else return temp * (9.0 / 5.0) + 32;
}
The getF and getC methods give me the same errors that refer me to the line they were declared in the header file, but the specific error is "declaration is incompatible with double degree::'methodname()' const"
Declarations and definitions need to match. Since you can't (and shouldn't) remove const from the declarations, add it to the definitions.
double degree::getC() const
{
...
}
double degree ::getF() const
{
...
}
I'm trying to run some test code to learn c++, but I am getting an error telling me the reverseDigits function was not declared in the main.cpp scope:
error: 'reverseDigits' was not declared in this scope.
But the #include "Solutions.h" header was included in main.cpp, so I thought that it would be in scope.
I have checkout other questions, but the answers all relate to problems with circular header file inclusion, which I don't think is the problem here.
Do you know why I am seeing that error?
Solution.h
#ifndef SOLUTION_H
#define SOLUTION_H
class Solution {
public:
Solution();
~Solution();
int reverseDigits(int x);
};
#endif // SOLUTION_H
Solution.cpp
#include "Solution.h"
#include <string>
Solution::Solution()
{
}
Solution::~Solution()
{
}
int Solution::reverseDigits(int x) {
std::string num_string = std::to_string(x);
std::string reversed_num_string {};
for (int i = num_string.length() - 1; i > 0; i--) {
reversed_num_string.push_back(num_string[i]);
}
return stoi(reversed_num_string);
}
main.cpp
#include <iostream>
#include "Solution.h"
int main()
{
int x {123};
int result = reverseDigits(x);
std::cout << result << std::endl;
return 0;
}
You declared reverseDigits as a member function of the Solution class, then defined it without qualifying it as a member of Solution (Edit: You've since changed it to match declaration and definition, but at point of use, you're trying to use an unqualified function, not a member of a Solution object). The declaration in the .h file is visible, but the definition in the .cpp is unrelated, and not visible to main.cpp.
Declare the function outside the class (since it's clearly unrelated to the class), and it should work, changing to:
class Solution {
public:
Solution();
~Solution();
};
int reverseDigits(int x); // NOT inside the class definition
I'll note: I have no idea why you have a Solution class at all. Defining reverseDigits doesn't require it, so I'm not seeing the point. If this is part of some automated evaluation framework, you'll have to give more details
Along with ShadowRanger's valid suggestion, I'll highlight upon how you could have used the data as part of your Solution class and applied the function on it.
Refactoring your class to
class Solution {
public:
Solution(int data);
~Solution();
int reverseDigits();
private:
int m_data;
};
Solution::Solution(int data)
{
m_data = data;
}
Solution::~Solution()
{
}
Even though you could have used std::reverse, fixing the error on the i>=0 is needed to have your own reverse function
int Solution::reverseDigits() {
std::string num_string = std::to_string(m_data);
std::string reversed_num_string {};
for (int i = num_string.length() - 1; i >= 0; i--) {
reversed_num_string.push_back(num_string[i]);
}
return stoi(reversed_num_string);
}
Now call it from your main() as
int main() {
int x = 123;
Solution sol(x);
std::cout << sol.reverseDigits() << std::endl;
return 0;
}
I just noticed something when creating functions. In the code:
#include <iostream>
using namespace std;
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
it will work because the function being called is on top of the caller, but if I put the function add() below the calling function in main() it won't work.
#include <iostream>
using namespace std;
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
and the compiler will tell me that the identifier add() cannot be found.
so why do we declare functions anyway? like this:
#include <iostream>
using namespace std;
int add(int a, int b = 20);
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b)
{
int r;
r = a + b;
return (r);
}
A definition is implicitly a declaration. And a declaration must come ahead of the use.
All functions need to be declared before they are used.
You can do that by either (1) writing a declaration, or (2) writing a definition.
Relying solely on (2) can be tempting but then you are bound to order your program in a particular way, and is occasionally impossible. For example, the following will not compile unless the comment is removed.
//void bar(int);
void foo(int n)
{
if (!n){
bar(n);
}
}
void bar(int n)
if (n){
foo(n);
}
}
int main()
{
foo(1);
}
No.
If the function definition appears before the function call, then prototype is not mandatory. Otherwise function prototype is necessary to let compiler know how to respond to a function when it is called.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
if the function definition appears after the function call then prototype is mandatory. because it tells the compiler to how to respond the function when it is called.
check the following example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int, int); // function prototype
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
and if the function definition is made before the function call then it is not mandatory to declare function prototype.
consider example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}
I am getting the error "error: Invalid use of AppleFarmer::AppleFarmer. I do not know why I am getting this error since I am not trying to pass any input into my Constructor. Is it possible I have an issue with my .h file? What am i doing wrong to get this error?
I have three different files, and I may also be having an issue with linking the code together as I am doing #include for a .cpp file. I am not sure if my code works aside from this error, but I am stuck on this error.
appleFarmerMain.cpp
#include<iostream>
#include "appleFarmer.cpp"
int main(){
AppleFarmer m;
int harvest;
int demand;
m.AppleFarmer();
while(m.endOfMonth()==false){
cout<<"Enter a harvest amount:"<<endl;
cin>>harvest;
m.harvestApples(harvest);
cout<<"Enter a demand:"<<endl;
cin>>demand;
m.sellApples(demand);
cout<<"Apple Inventory: "<<m.getInventory()<<endl;
m.updateCurrentDay();
}
return 0;
}
appleFarmer.cpp
#include "appleFarmer.h"
#include "<iostream>
using namespace std;
AppleFarmer::AppleFarmer(){
for(int i=0;i<30;i++){
sales[i]=0;
harvest[i]=0;
}
}
bool AppleFarmer::sellApples(int demand){
if(demand<= inventory){
sales[currentDay]=demand;
inventory=inventory-demand;
}
else{
sales[currentDay]=0;
}
}
void AppleFarmer::harvestApples(int dayHarvest){
harvest[currentDay]= dayHarvest;
inventory=inventory+dayHarvest;
}
bool AppleFarmer::endOfMonth(){
if (currentDay=maxDays){
return true;
}
else{
return false;
}
}
int AppleFarmer::updateCurrentDay(){
currentDay=currentDay+1;
}
int AppleFarmer::getInventory(){
return inventory;
}
double AppleFarmer::calculateAverageHarvest(){
}
double calculateAverageSales(){
}
void AppleFarmer::printSales(){
}
void AppleFarmer::printHarvest(){
}
appleFarmer.h
#ifndef APPLEFARMER_H
#define APPLEFARMER_H
class AppleFarmer
{
public:
AppleFarmer();
bool sellApples(int);
void harvestApples(int);
bool endOfMonth();
int updateCurrentDay();
int getInventory();
double calculateAverageHarvest();
double calculateAverageSales();
void printSales();
void printHarvest();
private:
int sales[30];
int harvest[30];
int maxDays = 30;
int currentDay = 0;
int inventory = 0;
};
#endif
In C++ you don't call the constructor on an object. That happens at object creation time. The line
m.AppleFarmer();
isn't needed. The constructor is implicitly called here:
AppleFarmer m;
You need to include appleFarmer.h instead of appleFarmer.cpp because the header file (with .h extension) contains the declaration while the .cpp file contains the implementation.
Then you need also to delete m.AppleFarmer(); because the constructor is called during the declaration (AppleFarmer m text line).
I've defined a util.h file with functions that i want to use throughout several different other files. This header has an include guard, however when i use it in two different files, I get a multiple definition of... error. What am i doing wrong?
I've read this but this pertains to variable declaration/definition. This answer seems more relevant but it's not clear to me how i can fix this.
// util.h
// include lots of standard headers
#include ...
#ifndef UTIL_H
#define UTIL_H
using namespace std;
// multiple definition of `randarr(int, int, int)`
int* randarr(int size, int min, int max) {
int *ret = new int[size];
for (int i=0; i<size; i++)
ret[i] = (int) (((double) rand() / RAND_MAX) * max) + min;
return ret;
}
// no error
template<typename T> void printarr(T* v, int begin, int end) {
for (int i=begin; i<end; i++)
cout << v[i] << " ";
cout << endl;
}
// multiple definition of `is_prime(int)`
bool is_prime(int n) {
if (n == 2 || n == 3 || n == 5) return true;
if (n <= 1 || (n&1) == 0) return false;
for (int i = 3; i*i <= n; i += 2)
if (n % i == 0) return false;
return true;
}
#endif
// example.cpp
#include ...// lots of standard includes
#include "util.h"
void f() {
randarr(...);
printarr(...);
is_prime(...);
...
}
// Main.cpp
#include "util.h"
int main() {
}
The include guards are not the cause of the error; you're violating the One Definition Rule. Since util.h is being included in 2 source files, the translation units created after preprocessing each source file will contain a definition of each of the functions, thus leading to the multiple definition error.
To get rid of the error, mark the functions inline
inline int* randarr(int size, int min, int max) {
// ...
}
template<typename T>
inline void printarr(T* v, int begin, int end) {
// ...
}
inline bool is_prime(int n) {
// ...
}
You are getting a linker error, not a compiler error. You have implemented the function randarr() in your util.h file, which means the compiler sees a copy of randarr() in each of example.cpp and Main.cpp. When the linker goes to link these together, it complains because you're not permitted to have more than one definition of the same function.
You have two choices:
declare randarr() as inline in the header file
move the definition for randarr() to a util.cpp file
Apply the same fix to is_prime().
You defined functions in a header file. This means, the code for these functions are included in both example.cpp and in Main.cpp. And it also means the code will be generated twice. This is the reason for the "multiple definition" error.
When you define the functions randarr() and is_prime() only once in a separate util.cpp, the errors will be gone.
Your header should only contain the prototype of your function. A prototype describes your function to other files, but do not implement it. The only exception is the template, because each template specialisation is build upon compile time.
If you implement your function in your header file, at linker time, you will find multiple times the function content, and that is why you are facing an error.
Move the implementation of randarr and is_prime to another file, and transform you util.h to :
#ifndef UTIL_H
#define UTIL_H
using namespace std;
int* randarr(int size, int min, int max);
template<typename T> void printarr(T* v, int begin, int end) {
for (int i=begin; i<end; i++)
cout << v[i] << " ";
cout << endl;
}
bool is_prime(int n);
#endif