Why the C++ linker doesn’t complain about missing definitions of theses functions?

I have written this code:

// print.h
#pragma once

#ifdef __cplusplus
#include <string>

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

#endif

void print();

And the source file:

// 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!");
}

And the driver program:

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

int main(){

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

  std::cout << 'n';
}

When I compile:

gcc -c print.cxx && g++ print.o main.cxx -o prog
  • The program works just fine but what matter me a lot is:

I compiled print.cxx using gcc which doesn’t define the C++ version print(double) and print(std::string). So I get print.o that contains only the definition of the C version of print().

  • When I used G++ to compile and build the program I passed print.o to it along with the source file main.cxx. It produces the executable and works fine but inside main.cxx I called the C++ versions of print (print(double) and print(std::string)) and these ones are not defined in prnint.o because it has been compiled using GCC and because of the macro __cplusplus (conditional compilation). So how come that the linker doesn’t complain about missing definitions of those functions?? Thank you!

Answer

I compiled print.cxx using gcc which doesn’t define the C++ version…

Not quite. gcc and g++ both invoke the same compiler suite. And the suite has a set of file extensions it automatically recognizes as either C or C++. Your *.cxx files were all compiled as C++, which is the default behavior for that extension.

You can use the -x option to override the default behavior.