make初试

来源:互联网 发布:iptables禁止端口访问 编辑:程序博客网 时间:2024/06/01 09:43

在linux下进行C++编程,makefile是必须掌握的自动化编译工具,之前在实验室总是看师兄们写的makefile,自己从来没写过。

这次自己亲自试试makefile的编写。

先从最简单的开始,所用的程序是经典的约瑟夫环的问题。有三个文件 josefu.h josefu.cpp main.cpp

代码如下

josefu.h:
#include<iostream>using namespace std;struct Node{        int data;        Node *next;};class josefu{ public:        josefu(int n);        void result(int m,int n); private:        Node *head;};


josefu.cpp

#include<iostream>#include"josefu.h"using namespace std;josefu::josefu(int n){        head=new Node;        //head->next=NULL;        head->data=1;        Node *s=head;        for(int i=2;i<=n;i++)        {                Node *p=new Node;                p->data=i;                p->next=NULL;                s->next=p;                s=s->next;        }        s->next=head;}void josefu::result(int m,int n){        Node *p=head;        cout<<"输入的顺序是:"<<endl;        for(int j=1;j<=n;j++)        {                cout<<p->data<<" ";                p=p->next;        }        cout<<endl;        p=head;        cout<<"输出的顺序为:"<<endl;        while(p)        {                for(int k=1;k<m-1;k++)                {                        p=p->next;                }                cout<<p->next->data<<" ";                Node *s=p->next;                p->next=s->next;                s->next=NULL;                delete s;                p=p->next;        }        cout<<endl;}

main.cpp:

#include<iostream>#include"josefu.h"using namespace std;int main(){        int m,n;        while(1)        {                cout<<"请输入总人数n,和顺序m:"<<endl;                cin>>n>>m;                josefu ob1(n);                ob1.result(m,n);        }        return 0;}

makefile 为

main:main.o josefu.o        g++ -g -o main main.o josefu.omain.o:main.cpp josefu.h        cc -c main.cppjosefu.o:josefu.cpp josefu.h        cc -c josefu.cpp ~                           

编译之后生成main程序并能成功执行。

几个问题:

一开始我在main函数里include 的是josefu.cpp 然后按照上面的makefile make之后会报错

josefu.o: In function `josefu::josefu(int)':
josefu.cpp:(.text+0x0): multiple definition of `josefu::josefu(int)'
main.o:main.cpp:(.text+0x0): first defined here
josefu.o: In function `josefu::result(int, int)':
josefu.cpp:(.text+0x86): multiple definition of `josefu::result(int, int)'
main.o:main.cpp:(.text+0x86): first defined here
josefu.o: In function `josefu::josefu(int)':
josefu.cpp:(.text+0x0): multiple definition of `josefu::josefu(int)'
main.o:main.cpp:(.text+0x0): first defined here
collect2: ld 返回 1
make: *** [main] 错误 1

之后我将main 函数改成inlcude"josefu.h“后,程序就能够顺利编译通过了

这主要是因为两个.cpp文件中,都包含头文件,那么在编译的时候就会造成重复定义的问题,导致编译错误,因此在需要包含其他文件时,只要包含.h头文件即可,而不要去包含负责实现的.cpp文件

http://www.cnblogs.com/zhaoxb1982/archive/2009/08/07/1540713.html

这篇文章解答了一部分疑问


原创粉丝点击