c++ - 使用 main() 重用文件中的类

标签 c++ program-entry-point redefinition

如何重用文件中已有 main 方法的类?例如。我想在我自己的程序 main.cpp 中使用另一个开发人员在 foo.cpp 中编写的 struct foo:

//-- 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 不会使用 g++ 4.4.4 编译,给出错误:

main.cpp: In function "int main()":
main.cpp:2: error: redefinition of "int main()"
foo.cpp:4: error: "int main()" previously defined here

我无法从 foo.cpp 中提取主要方法,因为我不控制该代码。在我处理的实际代码库中,struct foo 更复杂,所以我不能将它复制到 main.cpp 中,因为它无法维护。

最佳答案

在编译 foo.cpp;即,

g++ -Dmain=not_main foo.cpp

关于c++ - 使用 main() 重用文件中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7857526/

相关文章:

c - C启动例程需要什么?

C - 在数组中存储 main() 参数

c++ - 忽略头文件中的 main

c++ - 在 main 之前退出程序是否是明确定义的行为?

c++ - 类重新定义错误 C++

c++ - 为什么此代码不会导致重定义错误?

c++ - 析构函数必须做与构造函数对静态成员所做的相反的事情吗?

c++ - log4cplus是否支持xml配置文件和条件日志记录?

c++ - 星号不是字符常量?

c++ - C++中的自定义异常,用于对函数的无效输入