c++中如何在主函数中调用其他文件内的函数?

linux下c++中如何在主函数中调用其他文件内的函数?

这个作用不巴拉巴拉了,直接上干货!

需要四个文件: a.cpp包含一个被调用的函数,myhead.h预定义这个函数,3.b.cpp主函数,4.Makefile文件。
1.a.cpp
#include "myhead.h"
#include <iostream>
using namespace std;
int myfun(int a,int b){
         std::cout<<a+b<<std::endl;
        return 0;
}
2.myhead.h
#ifndef A_H_
#define A_H_
int myfun(int a,int b);
#endif
3.b.cpp
#include "myhead.h"
#include <iostream>
int main(int argc, char** argv){
  int a=2,b=3;
  myfun(a,b);
  return 0;
}
4.Makefile
CXX=g++
Objects=b.o a.o
myrun:$(Objects)
        $(CXX) -o myrun $(Objects)
b.o:b.cpp myhead.h
        $(CXX) -c b.cpp
a.o:a.cpp myhead.h
        $(CXX) -c a.cpp

5.linux 命令行下:
make
./myrun

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
主函数调用单链表,需要先定义并初始化一个链表的头节点。然后根据需要,逐个插入节点,构建链表的过程。可以使用一个循环,不断地通过用户输入或其他方式获取节点的值,并将新节点插入到链表的尾部。 典型的、简单的调用单链表的主函数如下所示: ```C++ #include <iostream> using namespace std; // 定义单链表的节点结构 struct ListNode { int val; // 节点的值 ListNode* next; // 指向下一个节点的指针 ListNode(int x) : val(x), next(NULL) {} // 构造函数 }; // 构建单链表 ListNode* buildLinkedList() { ListNode* head = new ListNode(0); // 头节点 ListNode* p = head; // 当前节点 int n; // 用于记录节点的值 cout << "请输入节点的值 (输入 0 结束):" << endl; cin >> n; while (n != 0) { ListNode* newNode = new ListNode(n); // 新建节点 p->next = newNode; // 将新节点连接到当前节点的后面 p = p->next; // 更新当前节点为新节点 cout << "请输入节点的值 (输入 0 结束):" << endl; cin >> n; } return head->next; // 返回链表的首节点 } // 打印链表 void printLinkedList(ListNode* head) { ListNode* p = head; cout << "链表的值为: "; while (p != NULL) { cout << p->val << " "; p = p->next; } cout << endl; } int main() { ListNode* head = buildLinkedList(); // 构建链表 printLinkedList(head); // 打印链表 return 0; } ``` 以上代码定义了一个用于构建单链表和打印链表的函数,分别为`buildLinkedList`和`printLinkedList`。在主函数,先调用`buildLinkedList`函数构建链表,然后再调用`printLinkedList`函数打印链表的值。 运行该程序,用户可以根据提示输入节点的值,直到输入0为止,构建完成后将会显示链表的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值