C,CPP,汇编综合例程
文件结构:
asm_with_c_with_cpp/
├── a.out
├── makefile
├── obj
│ ├── asm_base.o
│ ├── main_c.o
│ └── main_cpp.o
├── README.md
└── src
├── asm
│ └── asm_base.S
├── c
│ └── main_c.c
├── cpp
│ └── main_cpp.cpp
└── inc
├── asm.h
├── main_c.h
└── main_cpp.h
# src/asm/asm_base.S
.text
.globl asm_add
.globl asm_sub
asm_add:
push %ebp
mov %esp,%ebp
mov 0x8(%ebp),%edx
mov 0xc(%ebp),%eax
add %edx,%eax
pop %ebp
ret
asm_sub:
push %ebp
mov %esp,%ebp
mov 0x8(%ebp),%eax
sub 0xc(%ebp),%eax
pop %ebp
ret
// src/inc/asm.h
#ifndef __INC_ASM_H__
#define __INC_ASM_H__
#ifdef __cplusplus
extern "C" {
#endif
extern int asm_add(int a, int b);
extern int asm_sub(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
// src/c/main_c.c
#include "asm.h"
#include "main_c.h"
#include "main_cpp.h"
int main_c(){
int a = 10;
int b = 20;
int c = 0;
c = asm_add(a, b);
c = c_add(a, b);
c = cpp_add(a, b);
main_cpp();
return 0;
}
int c_add(int a, int b){
return a + b;
}
int c_sub(int a, int b){
return a - b;
}
// src/inc/main_c.h
#ifndef __MAIN_C_H__
#define __MAIN_C_H__
#ifdef __cplusplus
extern "C" {
#endif
int main_c(void);
int c_add(int a, int b);
int c_sub(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
// src/cpp/main_cpp
#include "asm.h"
#include "main_cpp.h"
#include "main_c.h"
class Rect
{
private:
int length;
int width;
public:
Rect();
Rect(int len, int wid);
int getArea(void);
// ~Rect(){}
};
Rect::Rect(){
length = 0;
width = 0;
}
Rect::Rect(int len, int wid){
length = len;
width = wid;
}
int Rect::getArea(void){
return length * width;
}
// Rect::~Rect(){}
int main_cpp(void){
int a = 10;
int b = 20;
int c = 0;
c = asm_add(a, b);
c = c_add(a, b);
c = cpp_add(a, b);
Rect rect(9, 9);
c = rect.getArea();
c = asm_add(a, b);
c = c_add(a, b);
c = cpp_add(a, b);
main_c();
return 0;
}
int cpp_add(int a, int b){
return a + b;
}
int cpp_sub(int a, int b){
return a - b;
}
// src/inc/main_cpp.h
#ifndef __MAIN_CPP_H__
#define __MAIN_CPP_H__
#ifdef __cplusplus
extern "C" {
#endif
int main_cpp(void);
int cpp_add(int a, int b);
int cpp_sub(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
Inc = -Isrc/inc
OBJINC = obj
ASM = gcc
ASMFLAGS = -ggdb -m32
CC = gcc
CFLAGS = -ggdb -m32
CPP = g++
CPPFLAGS = -ggdb -m32
LD = ld
LDFLAGS = -m elf_i386
all:
$(CPP) $(Inc) $(CPPFLAGS) -c ./src/cpp/main_cpp.cpp -o $(OBJINC)/main_cpp.o
$(CC) $(Inc) $(CFLAGS) -c ./src/c/main_c.c -o $(OBJINC)/main_c.o
$(ASM) $(Inc) $(ASMFLAGS) -c ./src/asm/asm_base.S -o $(OBJINC)/asm_base.o
$(LD) $(LDFLAGS) -e main_cpp $(OBJINC)/main_cpp.o $(OBJINC)/main_c.o $(OBJINC)/asm_base.o
clean:
rm $(OBJINC)/*.o
gdb:
gdb a.out --tui