nbaosullivan
nbaosullivan

Reputation: 4144

Can't access function from main file from header file C++

I don't know why I can't access the function clearConsole() from my .cpp file from the header files, I guess I'm calling it wrong? How do I target the main file from a header file? I try to call the clearConsole() function after the user input in the addCustomer() functinon in customer.h.

Main.cpp

// OTS.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;

#include "customer.h"

// Clear function specific to Windows 
// Cross platform alternatives are more convoluted to reach desired effect, so have not been included
void clearConsole()
{
    #ifdef _WIN32
    system("cls");
    #endif
}

Customer.h

//customer.H
//The object class customer

   class customer
    {
    //...
    clearConsole();
    }

Upvotes: 0

Views: 3620

Answers (3)

TheComputerGuy
TheComputerGuy

Reputation: 11

I also had this problem in my kernel that I'm writing in C,C++, and Assembly. I was able to fix this problem by telling the ld command to allow shared variables and functions using the -shared flag. In gcc you would just do the same thing because gcc is a linker, assembly, c compiler and a c++ compiler.

Upvotes: 0

Tchesko
Tchesko

Reputation: 21

Move your clearConsole() method to the header file (I think is not under discussion the implementation under .header files that I actually disagree, but anyway...), and change the system message to the specific one you need, as follows:

#ifndef _WIN32
#include <syscall.h>
#endif

void clearConsole(){
    #ifdef _WIN32
    system("cls");
    #else
    system("clear");
    #endif
}

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258648

If your files are linked together, a forward declaration of the functions should be enough.

Customer.h

//customer.H
//The object class customer

void clearConsole(); // <--- declare function

class customer
{

//....

};

But this structure looks wrong. I would declare the function in a different header, inside a namespace, and define it in a corresponding implementation file:

clearconsole.h

namespace ConsoleUtils
{
    void clearConsole();
}

clearconsole.cpp

namespace ConsoleUtils
{
    void clearConsole()
    {
    }
}

Upvotes: 4

Related Questions