-1

I'm trying to figure out why this is not working. I want to do like in Java where main is a static function in a class but this is producing unresolved external symbol error:

 static class MainClass
{
     public:
    static int _tmain(int argc, char* argv[])
    {
        return 0;
    }
};

Why doesn't this work?

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557

7 Answers7

10

C++ does not work like that.
You need main as a function:

int main(int argc,char* argv[])
{
    //STUFF
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
6

Because _tmain is mangled in the binary with the class name MainClass in it, so multiple classes could have a function _tmain in them and not conflict. It's not got the same mangled name as ::_tmain is going to have.

I remember that with an earlier version of MSVC, it accepted the following without a linker error which ended up accidentally as a result of macro expansion in my code base once

namespace bar {
  int main() { }
}

It apparently treated the name main specially and didn't mangle it or mangle it the same as ::main. But such a thing is not Standard conformant. Like in the class case, such a function is completely unrelated to the main function.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
1

_tmain is called from CRT. You need to set in your linker an entry point to another function that will call MainClass::_tmain instead.

ssianky
  • 97
  • 7
1

Because, in C++, you cannot put an entry point inside a class. This answer might help.

Community
  • 1
  • 1
KMån
  • 9,896
  • 2
  • 31
  • 41
1

Why doesn't that work? Because it's not C++.

struct MainClass {
  static int main(int argc, char** argv) {
    return 0;
  }
};

int main(int argc, char** argv) {
  return MainClass::main(argc, argv);
}
0

It's not really C++, so much as the standard linker process which is looking for an export of a specific name (with C-style linkage). The specific export varies based on the compiler and executable type, but the format is specific for each type. For example, Windows GUI exe's have different entry points than console, and specific for ASCII or UNICODE. But the linker is always looking for a function with a specific link name, which is why a static member won't work.

Nick
  • 6,808
  • 1
  • 22
  • 34
0

You always need main() defined as a global function. This is where the program always starts in C++. You could simple call your static class function from main and pass on the variables if you really want to:

class MainClass
{
     public:
    static int _tmain(int argc, char* argv[])
    {
        return 0;
    }
};

int main(int argc, char* argv[]) {
   return MainClass::_tmain(argc, argv);
}
JohnPS
  • 2,518
  • 19
  • 17