Skip to content

Instantly share code, notes, and snippets.

@princewang1994
Created June 30, 2018 14:11
Show Gist options
  • Save princewang1994/6c615efd61574d88dd1aa7ab872730e2 to your computer and use it in GitHub Desktop.
Save princewang1994/6c615efd61574d88dd1aa7ab872730e2 to your computer and use it in GitHub Desktop.
C++使用Makefile编译
#include<stdio.h>
#include"MyClass.h"
//调用MyClass需要两个东西
// 1. MyClass.h,需要知道里面有什么函数,有什么类
// 2. 由MyClass.h和MyClass.cpp编译出来的静态库libhello.a
// 编译libhello.a的命令为 `g++ -c MyClass.cpp && ar -crv libhello.a MyClass.o`
// 也可以使用别人已经生成好的lib,前提是需要有.h文件
int main(){
MyClass m;
int a=5, b=6;
int add = m.add(a, b);
int sub = m.sub(a, b);
printf("%d + %d = %d\n", a, b, add);
printf("%d - %d = %d\n", a, b, sub);
return 0;
};
# 设置make命令入口
default_target: all
# 静态库build命令 make hello
hello:
g++ -c MyClass.cpp
ar -crv libhello.a MyClass.o
# all依赖hello
all: hello
g++ main.cpp -L . -l hello -o app
#make clean命令定义
clean:
rm *.o *.a app
//
// Created by Prince Wang on 2018/6/30.
// 实现Myclass里面的函数
//
#include "MyClass.h"
MyClass::MyClass() {
}
int MyClass::add(int a, int b) {
return a + b;
}
int MyClass::sub(int a, int b) {
return a - b;
}
//
// Created by Prince Wang on 2018/6/30.
// 定义一个class的头文件
//
#ifndef NEW_MYCLASS_H //防止循环定义
#define NEW_MYCLASS_H
class MyClass {
public:
MyClass();
int add(int a, int b);
int sub(int a, int b);
};
#endif //NEW_MYCLASS_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment