问题描述:

How can I reuse a class that is in a file that already has a main method? E.g. I would like to use struct foo that another developer wrote in foo.cpp in my own program, main.cpp:

//-- foo.cpp --

struct foo {

int bar;

};

int main() {

return 0;

}

//-- end foo.cpp --

//-- main.cpp --

#include "foo.cpp"

int main() {

foo f;

f.bar = 1;

return f.bar;

}

//-- end main.cpp

main.cpp will not compile using g++ 4.4.4, giving the errors:

main.cpp: In function "int main()":

main.cpp:2: error: redefinition of "int main()"

foo.cpp:4: error: "int main()" previously defined here

I cannot extract the main method from foo.cpp because I do not control that code. In the actual codebase I am dealing with, struct foo is more complicated so I cannot copy it into main.cpp, since it would be unmaintainable.

网友答案:

Use a preprocessor define to make main into a macro that expands to, for example, not_main, while you're compiling foo.cpp; i.e.,

g++ -Dmain=not_main foo.cpp
网友答案:

Non-coding solution: go talk to the people who maintain the code in question. Offer to refactor it for them!

网友答案:

place the struct foo inside a header

foo.h
#ifndef _STRUCT_FOO
#define _STRUCT_FOO
struct foo {
  int bar;
};
#endif

include that wherever you need it.

相关阅读:
Top