[英]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? 我不知道为什么我无法从头文件的.cpp文件中访问函数clearConsole(),我想这是错误的吗? 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.
我尝试在用户在customer.h中的addCustomer()函数中输入用户之后调用clearConsole()函数。
Main.cpp 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
//customer.H
//The object class customer
class customer
{
//...
clearConsole();
}
If your files are linked together, a forward declaration of the functions should be enough. 如果文件链接在一起,则函数的前向声明就足够了。
Customer.h 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: 我将在
namespace
内的其他头文件中声明该函数,并在相应的实现文件中对其进行定义:
clearconsole.h clearconsole.h
namespace ConsoleUtils
{
void clearConsole();
}
clearconsole.cpp clearconsole.cpp
namespace ConsoleUtils
{
void clearConsole()
{
}
}
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: 将您的clearConsole()方法移至头文件(我实际上并未在讨论我实际上不同意的.header文件下的实现,但是无论如何...),然后将系统消息更改为所需的特定消息,如下所示:
#ifndef _WIN32
#include <syscall.h>
#endif
void clearConsole(){
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
I also had this problem in my kernel that I'm writing in C,C++, and Assembly. 我在用C,C ++和Assembly编写的内核中也遇到了这个问题。 I was able to fix this problem by telling the
ld
command to allow shared variables and functions using the -shared
flag. 通过告诉
ld
命令允许使用-shared
标志共享变量和函数,我能够解决此问题。 In gcc you would just do the same thing because gcc is a linker, assembly, c compiler and a c++ compiler. 在gcc中,您将做同样的事情,因为gcc是链接器,程序集,c编译器和c ++编译器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.