前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >g++编译链接多个文件

g++编译链接多个文件

原创
作者头像
村子里的设计师
发布2023-05-20 14:50:21
1.3K0
发布2023-05-20 14:50:21
举报
文章被收录于专栏:程序设计a

代码示例

main.cpp

代码语言:javascript
复制
#include "test1.h"

int main() {
        test1();
        return 0;
}

test1.h

代码语言:javascript
复制
#ifndef __TEST1_H
#define __TEST1_H

const int kVar = 1; // 测试不使用extern

void test1();

#endif

test1.cpp

代码语言:javascript
复制
#include <iostream>
#include "test1.h"

using namespace std;

void test1() {
        cout << "in test1: " << kVar << endl;
}

编译

代码语言:javascript
复制
g++ -c main.cpp test1.cpp

// -c                       Compile and assemble, but do not link.
// g++ -c 将为每个.cpp文件生成对应的目标文件,如下所示的main.o, test1.o
// $ ls
// main.cpp  main.o  test1.cpp  test1.h  test1.o

链接

代码语言:javascript
复制
g++ -o main main.o test1.o

// -o <file>                Place the output into <file>.
// g++ -o 对多个.o文件进行链接,生成.exe文件
// $ ls
// main.cpp  main.exe  main.o  test1.cpp  test1.h  test1.o

执行

代码语言:javascript
复制
// $ ./main

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码示例
    • main.cpp
      • test1.h
        • test1.cpp
        • 编译
        • 链接
        • 执行
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档