当前位置:网站首页>Mixed compilation of C and CC

Mixed compilation of C and CC

2022-07-05 04:04:00 1mmorta1

Problem principle

I always thought gcc The compiled file is C Type object file , It has nothing to do with the suffix of the source file . When doing a small experiment this time, I found that the form of the target file is determined by the suffix .

start.h

void start();

start.c

#include <stdio.h>
void start(){
    
    printf("start\n");
}

test.cc

#include <stdio.h>
#include <string.h>
#include "start.h"
int main(){
    
    printf("main\n");
    start();
}
*  personal_use gcc -c start.c test.cc 
*  personal_use ld start.o test.o -lc
ld: warning: cannot find entry symbol _start; defaulting to 00000000004002c0
test.o: In function `main': test.cc:(.text+0x11): undefined reference to `start()'
*  personal_use nm start.o
                 U _GLOBAL_OFFSET_TABLE_
                 U puts
0000000000000000 T start
*  personal_use nm test.o
                 U _GLOBAL_OFFSET_TABLE_
0000000000000000 T main
                 U puts
                 U _Z5startv

It can be seen that although they are all used gcc Compilation of , however test.cc The target file for is obviously cpp Formal ( its start Functional symbol It's decorated ), and start.c It is c Form of object file .
So when linking ,test.cc I can't find it _Z5startv This symbol , because test.o There is symbol Name is start .
To sum up , The essence of the problem is actually c and cpp The handling of symbols is different ,cpp Will be embellished with symbols , and c Can't , As a result, the same function in the source code will be different when it becomes a symbol , Cause ambiguity .

resolvent

  1. The simplest thing is to change them into Chengdu c Files or both cpp file , Of course, you can also use both g++ Compile Links ( All become cpp Type object file or c Type object file )

  2. You can put test.cc Modify your file

    #include <stdio.h>
    #include <string.h>
    #ifdef __cplusplus
    extern "C"
    {
          
    #endif
    #include "start.h"
    #ifdef __cplusplus
    }
    #endif
    int main(){
          
        printf("main\n");
        start();
    }
    

    In this way test.cc As stated in start The function uses c Type symbol, No ambiguity .

原网站

版权声明
本文为[1mmorta1]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140712237413.html