我们可以指定一些只在编译时g++ main.cpp而不是在运行时./a.out执行的指令吗?在 C/C++ 中

问题描述

#include<bits/stdc++.h>

using namespace std;

{
   // only run when we press ./a.out
   // instruction 1

}

{
  // only run when we press g++ main.cpp or gcc main.c
  // instruction 2
}



int main() {

    // other part of code

}
@H_502_3@

实际上我想在 .txt 文件中读/写。当我运行 g++ main.cpp 时,应该创建新的 .txt 文件,当我运行 ./a.out " fout

解决方法

您编写的代码描述了作为进程结果的程序行为(程序在执行时会做什么)。

你想要的是构建过程本身的一部分(除了编译/链接等之外还做了什么)。

如果您直接从命令行调用 g++,我想您无法实现目标。您必须使用 CMake(或 make 或任何其他构建系统)。执行此操作的确切方法取决于构建系统。