Simple question, how can I run a program having main inside a class?
I have a code:
MojSwiat2.cpp:
int Main::main() {
// code
return 0;
}
And MojSwiat2.h:
class Main {
public:
int main();
};
Main run;
int Main::main() { // with this I have error: function int Main::main(void) already has a body
run.main();
} // and without I got unresolved external symbol _main referenced in function __tmainCRTStartup
Reason I need to do this: Accessing protected members of class from main
By defining a normal main that only contains a call to your other function. Like this:
int main(int, char**) {
return Main().main();
}
int main(int argc, char* argv[])
{
Main m;
return m.main();
}
or if Main::main is declared static
int main(int argc, char* argv[])
{
return Main::main();
}
You still need to define main.
class my_app {
int main(int argc, char* argv[])
{
// ...
}
}
my_app app;
int main(int argc, char *argv[])
{
return app.main(argc, argv);
}
Related
Here is a reduced version of my code:
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
class MainView : public QMainWindow
{
public:
static MainView *Initialise(int argc, char **argv);
int Run() { return qApp->exec(); }
private:
MainView() { }
virtual ~MainView() { }
};
namespace
{
QApplication *s_app {nullptr};
MainView *s_instance {nullptr};
};
MainView *MainView::Initialise(int argc, char **argv)
{
if (nullptr == s_app) {
s_app = new QApplication(argc, argv);
}
if (nullptr == s_instance) {
s_instance = dynamic_cast<MainView *>(new MainView());
}
return s_instance;
}
class Framework
{
public:
Framework() { }
~Framework() { }
int Initialise(int argc, char **argv)
{
m_main_view = MainView::Initialise(argc, argv);
return 0;
}
int Run()
{
m_main_view->show();
return m_main_view->Run();
}
private:
MainView *m_main_view;
};
int main(int argc, char **argv)
{
Framework framework;
int result = 0;
// Weirdness here!!!!
MainView::Initialise(argc, argv); // Crashes even with this line.
result = framework.Initialise(argc, argv);
if (0 == result) {
result = framework.Run();
}
return result;
}
This code crashes when showing the MainWindow instance. In my full version of this code, where MainView inherits from a virtual interface class (so as to allow me to decouple the view and substitute a command line interface or a test interface) it doesn't crash unless I comment out the code marked as "weirdness here".
In this code, if I replace:
MainView::Initialise(argc, argv); // Crashes even with this line.
with:
if (nullptr == s_app) {
s_app = new QApplication(argc, argv);
}
then it works fine and doesn't crash.
Essentially if the application is instantiated within MainView::Initialise(), whether called from main() or from Framework::Initialise() then the program crashes, but if I initialise the application in main() first then it doesn't crash.
I don't want my main() function to have any knowledge of the UI at all, if possible, even taking my virtual base class interface into account. There should be no need and it makes main() messier than necessary.
So why is this crashing and how do I stop it?
There's a subtle difference between your invocation of the QApplication constructor in main() and the invocation in MainView::Initialise().
The documentation for the QApplication constructor says:
QApplication::QApplication(int &argc, char **argv)
< ... >
Note: argc and argv might be changed as Qt removes command line arguments that it recognizes.
So when invoking the constructor in MainView::Initialise(), you are actually passing a copy of the argc that came from main. Presumably, Qt stores a reference to this internally somewhere, causing it to crash when the QApplication later dereferences it during the construction of the window.
If you change the signature of both Initialise() functions to take a reference to argc, the program works without crashing.
I am trying to use weak function in a class in C++. Below is what I wrote:
#include <stdio.h>
#include <iostream>
class A {
public:
void func(int argc, char *argv[]) __attribute__((weak));
};
// optional definition:
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
if (a1.func){
a1.func(argc, argv);
} else {
printf("func() not available\n");
}
return 0;
}
But this gives below compilation error:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:21:16: error: cannot convert ‘A::func’ from type ‘void (A::)(int, char**)’ to type ‘bool’
if (a1.func){
^
If I move the func() outside a class and use gcc instead of g++, it compiles fine and works as expected. Can someone please tell what's the problem. Basically I want to achieve calling some class functions only if they are available (an optional feature) without using Compiler flags in cpp file.
C++ has a standard mechanism for this. No need for linker tricks.
class Base {
public:
virtual void func(int argc, char *argv[])
{
printf("func() not available\n");
}
};
class A : public Base {
public:
#if 0
void func(int argc, char *argv[]) override;
#endif
};
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
a1.func(argc, argv);
}
I have a static method inside my class, which I use for a callback.
Inside this callback I want to add a value to result.
This seems not to be possible because of the recast(?).
Is there a way to access the member variable result and add values to it after recasting, or do I need to think of a different way?
MyClass.h
class MyClass
{
public:
vector<string> result;
static int c_CB(void *data, int argc, char **argv, char **azColName);
int Callback(int argc, char **argv, char **azColName);
void Do(string query);
}
MyClass.cpp
void MyClass:Do(string query)
{
sqlite3_exec(this->dbResource, query.c_str(), this->c_CB , NULL, &this->errorMsg);
}
int MyClass::c_CB(void *NotUsed, int argc, char **argv, char **azColName)
{
MyClass* bar = reinterpret_cast<MyClass*>(NotUsed);
// after reinterpret cast, it does not work
//bar->result.insert(bar->result.end(), "foo");
// function call works
return bar->Callback(argc, argv, azColName);
}
int MyClass::Callback(int argc, char **argv, char **azColName)
{
cout << "working" << endl;
}
main.cpp
int main()
{
MyClass* cl = new MyClass();
cl->Do("something");
}
The documentation states that the fourth argument to sqlite3_exec is passed as the first argument of the callback.
Currently you are passing NULL, which you then cast to a MyClass* and attempt access the object, which results in undefined behaviour.
Use this as the fourth argument in place of NULL.
It seems you are trying to access a non-static member function from a static member callback function c_CB.
You were able to call a member function Callback but nothing from the class is accessible, but if I'm correct, the compiler just interpreted Callback as a static function.
If you actually breakpoint inside this function, you can see that none of your member variables actually have a memory address. And the current class, this is null
I'm not sure if the cout << statement still works or if its causing the problem
This is a possible solution to your issue, although it may not be the best one.
class MyClass
{
public:
vector<string> result;
static int c_CB(void *data, int argc, char **argv, char **azColName);
int Callback(int argc, char **argv, char **azColName);
void Do(string query);
void MemberFunction()
{
cout << "working" << endl;
}
static MyClass* currentClass; //Add a static class pointer and assign your class address to it before firing the callback.
}
MyClass* MyClass::currentClass = NULL;
void MyClass:Do(string query)
{
sqlite3_exec(this->dbResource, query.c_str(), this->c_CB , NULL, &this->errorMsg);
}
int MyClass::c_CB(void *NotUsed, int argc, char **argv, char **azColName)
{
MyClass* bar = reinterpret_cast<MyClass*>(NotUsed);
// after reinterpret cast, it does not work
//bar->result.insert(bar->result.end(), "foo");
// function call works
return bar->Callback(argc, argv, azColName);
}
int MyClass::Callback(int argc, char **argv, char **azColName)
{
currentClass->MemberFunction();
}
int main()
{
MyClass* cl = new MyClass();
MyClass::currentClass = this;
cl->Do("something");
}
I get identifer not found error for "startProcess":
int main(int argc, char* argv[])
{
bool result=startProcess(argc, argv);
return 0;
}
bool startProcess(int argc, char* argv[])
{
}
But why?
Functions need to be at least declared before you use them, if not defined. Try putting this at the top of your file.
bool startProcess(int argc, char* argv[]);
The above is a declaration, you're telling the compiler that at some point, you're going to provide a definition for the function, which is this:
bool startProcess(int argc, char* argv[])
{
code here...
}
This difference between a declaration and a definition is important for being able to separate your code into separate files. If you had placed your definition of startProcess in a different file, the compiler would never actually see it while compiling the file that contains main. However, with the declaration, you're making a promise that it exists somewhere.
You haven't declared that function before main(), so the compiler is unaware of the existence of startProcess at the point of call:
bool startProcess(int argc, char* argv[]); // <== Informs the compiler about
// the existence of startProcess
// (and about its signature)
int main(int argc, char* argv[])
{
bool result = startProcess(argc, argv); // OK because of the declaration
// above: the compiler knows that
// somewhere (possibly in another
// translation unit) the definition
// of startProcess is provided
return 0;
}
bool startProcess(int argc, char* argv[])
{
// ...
}
Alternatively, you can put the definition directly before main():
bool startProcess(int argc, char* argv[])
{
// ...
}
int main(int argc, char* argv[])
{
bool result = startProcess(argc, argv);
return 0;
}
You should put the declaration of startProcess before main if you would like to put definition of it after main.
bool startProcess(int argc, char* argv[]); //declare here
int main(int argc, char* argv[])
{
bool result=startProcess(argc, argv);
return 0;
}
bool startProcess(int argc, char* argv[])
{
}
or you can put the definition of startProcess directly before main.
Make a prototype before your main function.
bool startProcess(int argc, char* argv[]);
I came across this error:
main.cpp:22:34: error: ‘getTotalSystemMemory’ was not declared in this
scope
#include <unistd.h>
#include <cstdlib>
#include <stdio.h>
#include <iostream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
cout << "Hello World! \n";
cout << getTotalSystemMemory();
return 0;
}
long getTotalSystemMemory()
{
long pages = sysconf(_SC_PHYS_PAGES);
long page_size = sysconf(_SC_PAGE_SIZE);
return pages * page_size;
}
I assumed the the method ‘getTotalSystemMemory’ is in scope since it is within the same class
You need to provide at least a declaration before you use the function:
long getTotalSystemMemory(); //declaration
int main(int argc, char** argv) {
//...
cout << getTotalSystemMemory();
//...
}
long getTotalSystemMemory()
{
//...
}
You have to declare the function first with C/C++.
Put this before main
long getTotalSystemMemory();
You must "prototype" the function if you are going to be defining it below int main() {}:
long getTotalSystemMemory();
int main() {
/* ....... */
getTotalSystemMemory();
}
long getTotalSystemMemory() {}
in c++ you must write the function before the functions that use it.
if you don't want to write the function in the top, you must put a prototype before.
prototypes look like that:
<return-value> <function name> (<parameters type>);