C ++:使用GCC编译器链接文件 [英] C++: Linking files with GCC compiler

查看:285
本文介绍了C ++:使用GCC编译器链接文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个文件:myh.h; my.cpp; use.cpp。以下是文件的内容:



myh.h

  extern int foo; 
void print_foo();
void print(int);

my.cpp

  #includemyh.h
#include< iostream>
void print_foo()
{
std :: cout<< foo<< std :: endl;
}
void print(int i)
{
std :: cout<< i< std :: endl;
}

use.cpp
$ b

  #includemyh.h
int main()
{
foo = 7;
print_foo();
print(99);
return 0;
}

GCC发出以下错误:

  my.o:my.cpp :(。text + 0x7):未定义的引用`foo'
use.o:use.cpp :(。文本+ 0x10):未定义的引用`foo'
collect2:ld返回1退出状态

我使用-c命令编译文件,它不给出错误。我使用以下命令链接:

  g ++ -o final my.o use.o 

这里有什么问题,我读了其他类似问题的主题,这里的情况只是奇怪.....



对于好奇这是从Stroustrup的书使用C ++的编程原理的运动训练



编辑:我做了dasblinkenlight说,在use.cpp我在foo前面添加了一个int(所以现在foo被定义),但我仍然得到这个错误:

  my.o:my.cpp :(。text + 0x7):未定义引用`foo'
collect2:ld返回1退出状态

这告诉我它在my.cpp中没有定义吗?

解决方案

如果我必须定义它到底什么是将它包含在头文件中,

由于您已声明 foo ,但您从未定义

extern int foo 只是一个声明;它不会导致为 foo 变量分配内存,只承诺你会在其他地方做它。要修复它,您需要将此行添加到一个cpp文件,如下所示:

  #includemyh.h 
int foo;
int main()
{
foo = 7;
print_foo();
print(99);
return 0;
}


I have three files : myh.h; my.cpp; use.cpp. Here are the contents of the files:

myh.h

extern int foo;
void print_foo();
void print(int);

my.cpp

#include "myh.h"
#include <iostream>
void print_foo()
{
    std::cout<<foo<<std::endl;
}
void print(int i)
{
    std::cout<<i<<std::endl;
}

use.cpp

#include "myh.h"
int main()
{
    foo=7;
    print_foo();
    print(99);
    return 0;
}

GCC spews out the following error:

my.o:my.cpp:(.text+0x7): undefined reference to `foo'
use.o:use.cpp:(.text+0x10): undefined reference to `foo'
collect2: ld returned 1 exit status

I compile the files using the -c command and it doesn't give errors. I link using the following command:

g++ -o final my.o use.o

What is the problem here, I read other topics with similar problems, and the case here is just strange .....

For the curious this is an exercise drill from Stroustrup's book Programming principles of using C++

Edit: I did as dasblinkenlight said, and in use.cpp I added an int in front of foo (so now foo is defined), but I still get this error:

my.o:my.cpp:(.text+0x7): undefined reference to `foo'
collect2: ld returned 1 exit status

Which tells me that it is not defined in my.cpp also? If I have to define it everywhere what is the point of including it in the header file, or how should this be approached more appropriately?

解决方案

You get a linker error because you declared foo, but you never defined it.

extern int foo is only a declaration; it does not cause allocation of memory for the foo variable, only promises that you will do it at some other place. To fix it, you need to add this line to one of the cpp files, like this:

#include "myh.h"
int foo;
int main()
{
    foo=7;
    print_foo();
    print(99);
    return 0;
}

这篇关于C ++:使用GCC编译器链接文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆