简体   繁体   English

在Linux上使用静态链接时未定义对g ++中函数的引用

[英]Undefined reference to function in g++ while using static linking on Linux

I am learning programming under Linux, and I faced the following problem during linking. 我正在学习Linux下的编程,并且在链接期间遇到以下问题。

My directory structure 我的目录结构

libraries
    |-- archive_sample
    |           |-- calc.h
    |           |-- calc.cpp
    |           |-- makefile
    |
    |-- test_archive
                |-- main.cpp
                |-- makefile

calc.h 计算值

#ifndef __CALC__H__
#define __CALC__H__

int add(int a, int b);
int sub(int a, int b);

#endif

calc.cpp calc.cpp

#include "calc.h"

int add(int a, int b)
{
  return (a + b);
}

int sub(int a, int b)
{
  return (a - b);
}

File archive_sample/makefile: 文件archive_sample / makefile:

libcalc.a : calc.o
    ar rcs libcalc.a calc.o

calc.o : calc.cpp calc.h
    g++ $(CFLAGS) -c calc.cpp

clean :
    rm -f libcalc.a calc.o

When I run "make" from archive_sample directory, it executes successfully and calc.o and libcalc.a are created in the same directory. 当我从archive_sample目录运行“ make”时,它成功执行,并且calc.o和libcalc.a在同一目录中创建。

main.cpp main.cpp

int main()
{
  int a, b;

  std::cin >> a >> b;
  std::cout << "a + b : " << add(a, b) << std::endl;
  std::cout << "a - b : " << sub(a, b) << std::endl;

  return (0);
}

Compiling with 编译

g++ -c -I../archive_sample main.cpp

succeeds and main.o is created. 成功并创建了main.o。 However linking with 但是与

g++ -L../archive_sample -lcalc main.o -o test

gives the following error: 给出以下错误:

main.o: In function main:
main.cpp:(.text+0x3e): undefined reference to add(int, int)
main.cpp:(.text+0x84): undefined reference to sub(int, int)
collect2: error: ld returned 1 exit status

Where am I going wrong? 我要去哪里错了?

Also "make" is also not working for the following makefile. 同样,“ make”也不适用于以下makefile。

test_archive/makefile test_archive / makefile

test : main.o
    g++ -L../archive_sample -lcalc main.o

main.o : main.cpp calc.h
    g++ $(CFLAGS) -c -I../archive_sample main.cpp

clean :
    rm -f test *.o

with error 有错误

make: *** No rule to make target `calc.h', needed by `main.o'.  Stop.

How can I fix this problem? 我该如何解决这个问题?

For the first error, since main.cpp and archive_sample are in the same directory, you shouldn't specify -Larchive_sample rather than -L../archive_sample . 对于第一个错误,由于main.cpparchive_sample在同一目录中,因此您不应指定-Larchive_sample而应指定-L../archive_sample

For the second error, your calc.h is in the archive_sample directory, so the dependency should be listed as archive_sample/calc.h . 对于第二个错误,您的calc.harchive_sample目录中,因此依赖项应列为archive_sample/calc.h

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM