从命令行为源文件定义宏

Defining macros for a source file form the command line

我正在尝试使用 -D 标志从 ubuntu 系统的命令行为源文件定义一个宏。 源文件是:

#include<iostream>
using namespace std;

int factorial(int n){
    if(n!=1){
    return(n * factorial(n-1));
    }
    else return 1;
    #ifdef DEEPAK

    cout<<"hello"<<endl;
    #endif
}
int main()
{
    factorial(4);
    return(0);
}

我输入的命令是:

gcc -Wall -DDEEPAK  factorial.cpp -o main

但是,我收到错误消息:

/tmp/cc4Ii5l2.o: In function `__static_initialization_and_destruction_0(int, int)':
factorial.cpp:(.text+0x63): undefined reference to `std::ios_base::Init::Init()'
factorial.cpp:(.text+0x72): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

如有任何帮助,我们将不胜感激。谢谢

您应该在命令中使用 g++ 而不是 gcc,因为默认情况下 gcc 不会 link 到 C++ STL,因此它给出了一个对 std::ios_base 的未定义引用。

g++ -Wall -DDEEPAK  factorial.cpp -o main