我正在阅读 C++ 入门书,我正在阅读第 19 章。外部链接。
因此,例如,如果我想从 C++ 链接到一个 C 函数,那么我声明该函数,external "C" void foo();
然后当我编译我的 C++ 程序时,我会发出如下内容:
gcc -c foo.c && g++ main.cxx foo.o -o prog
这工作得很好,另一方面我可以将我的C++
代码导出到C
例如。
- 但是只要
C++
编译器可以直接编译C
代码,我为什么还要将它声明为外部代码,为什么我需要使用它gcc
来编译该源代码?
这只是我的模拟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';
}
当我编译我的代码时,我发出:
gcc -c my_string.c && g++ main.cxx my_string.o -o prog
它工作得很好,但是如果我从extern "C"
标题中删除并将所有代码编译为C++
代码,它也可以正常工作:
g++ my_string.c main.cxx -o prog
- 我已经
extern "C"
从标题中删除my_string.h
并且工作正常。C
那么为什么只要C++
支持它,我就需要从外部链接到代码呢?