2

我写了这段代码:

// print.h
#pragma once

#ifdef __cplusplus
#include <string>

void print(double);
void print(std::string const&);
extern "C"

#endif

void print();

和源文件:

// print.cxx
#include "print.h"
#include <iostream>

void print(double x){
  std::cout << x << '\n';
}

void print(std::string const& str){
   std::cout << str << '\n';
}

void print(){
   printf("Hi there from C function!");
}

和驱动程序:

// main.cxx
#include "print.h"
#include <iostream>

int main(){

  print(5);
  print("Hi there!");
  print();

  std::cout << '\n';
}

当我编译时:

gcc -c print.cxx && g++ print.o main.cxx -o prog
  • 该程序运行良好,但我很重要的是:

print.cxx使用gcc未定义 C++ 版本print(double)print(std::string). 所以我得到print.o它只包含 C 版本的定义print()

  • 当我过去G++编译和构建程序时,我print.o将它与源文件一起传递给它main.cxx。它生成可执行文件并且工作正常,但在里面我调用了(和)main.cxx的 C++ 版本,这些版本没有定义,因为它是使用 GCC 编译的并且因为宏(条件编译)。那么为什么链接器不抱怨缺少这些函数的定义呢?谢谢!printprint(double)print(std::string)prnint.o__cplusplus
4

1 回答 1

6

print.cxx使用gcc未定义 C++ 版本进行编译...

不完全的。gcc并且g++都调用相同的编译器套件。该套件有一组文件扩展名,它会自动识别为 C 或 C++。您的*.cxx文件全部编译为 C++,这是该扩展的默认行为。

您可以使用该-x选项来覆盖默认行为。

于 2021-09-09T00:59:34.570 回答