Why do I need to link externally to C as long as C++ compilers support C code?

139 Views Asked by At

I am reading C++ primer and I'm on chapter 19. External linkage.

So for example if I want to link to a C function from C++ then I declare that function as external "C" void foo(); then when I compile my C++ program I issue something like:

gcc -c foo.c && g++ main.cxx foo.o -o prog

This works just fine and I can on the other hand export my C++ code to C for example.

  • But as long as a C++ compiler can compile directly C code, why I bother declare it as external and why I need to use gcc to compile that source?

Here is just my simulation of string.h:

// my_string.h
#ifndef MY_STRING_H_
#define MY_STRING_H_

#ifdef __cplusplus
    extern "C" {
#endif

    int my_strlen(char const*);
    int my_strcpy(char*, char const*);
    int my_strcmp(char const*, char const*);

#ifdef __cplusplus
    }

#endif
#endif

// my_string.c
#include "my_string.h"

int my_strlen(char const* cp){
   int sz = 0;
   for(char const* tmp = cp; *tmp; tmp++)
      ++sz;

   return sz;
}

int my_strcpy(char* buff, char const* cp){
    
   int i = 0;
   for(int sz = my_strlen(cp); i != sz; ++i)
      *(buff + i) = *(cp + i);

   return i;
}

int my_strcmp(char const* str1, char const* str2){

   int len1 = my_strlen(str1);
   int len2 = my_strlen(str2);

   if(len1 > len2)
      return 1;
   else if(len1 < len2)
      return -1;
   else
      return 0;
}

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

int main(){

   std::cout << my_strlen("Ahmed") << '\n';
   char name[10];
   my_strcpy(name, "Ahmed");

   std::cout << name << '\n';
}
  • When I compile my code I issue:

    gcc -c my_string.c && g++ main.cxx my_string.o -o prog
    

It works just fine but If I remove extern "C" frome the header and I compile all the code as a C++ code it works fine too:

  g++ my_string.c main.cxx -o prog
  • I've remove extern "C" from the header my_string.h and works fine. So Why I need to link externally to C code as long as C++ supports it?
0

There are 0 best solutions below