c++cexternal-links

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

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().


Solution

  • 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.