g++编译链接多个文件

头文件 mystack.h

/**
 * File mystack.h
 * Declare class Stack
 **/
#ifndef MYSTACK_H
#define MYSTACK_H

#include <iostream>
using namespace std;

enum Error_code { success, fail, underflow, overflow };
typedef char Stack_entry;

const int maxstack = 10;

class Stack
{
public:
    Stack();
    bool empty() const;
    Error_code pop();
    /**
     * the top of the Stack is returned in item
     **/
    Error_code top(Stack_entry& item) const;
    Error_code push(const Stack_entry& item);
    
private:
    int count;
    Stack_entry entry[maxstack];
};


#endif

预编译: g++ mystack.h


库文件 mystack.cpp

/**
 * File mystack.cpp
 **/

#include "mystack.h"
#include <iostream>

using namespace std;

Error_code Stack::push(const Stack_entry& item)
{
    Error_code outcome = success;
    if (count >= maxstack)
	outcome = overflow;
    else
	entry[count++] = item;
    return outcome;
}

Error_code Stack::pop()
{
    Error_code outcome = success;
    if (count == 0)
	outcome = underflow;
    else
	count--;
    return outcome;
}

Error_code Stack::top(Stack_entry& item) const
{
    Error_code outcome = success;
    if (count == 0)
	outcome = underflow;
    else
	item = entry[count - 1];
    return outcome;
}

bool Stack::empty() const
{
    bool outcome = true;
    if (count < 0)
	outcome = false;
    return outcome;
}

Stack::Stack()
{
    count = 0;
}
编译:g++ -c mystack.cpp -o mystack.o


main函数: stacktest.cpp

/**
 * File stacktest.cpp
 **/
#include "mystack.h"
#include <iostream>

using namespace std;

int main()
{
    Stack s;
    s.push('1');
    char top = 0;
    s.top(top);

    cout << top << endl;

    return 0;
}

编译并链接: g++ -o stacktest stacktest.cpp ./mystack.cpp

运行: ./stacktest



你可能感兴趣的:(File,Class)