Jump to content

Error compiling C++ program with C library


Recommended Posts

I've created 3 files: swap.h and swap.c

then make static library from it

 

 
gcc -Wall -c swap.c
ar -cvq libswap.a swap.o

Then I write 2 program to test this library: test_swap.c and test_swap.cpp

I compile

$ gcc -Wall -o testc test_swap.c libswap.a
$ ./testc
a = 100 | b = 1
$ g++ -Wall -o testcpp test_swap.cpp libswap.a
/home/user/tmp/cc2Lcf8G.o: In function `main':
test_swap.cpp:(.text+0x2b): undefined reference to `swap_int(int*, int*)'
collect2: ld returned 1 exit status

 

What's wrong with this in C++?

 

Here the source code

 

+ swap.h

#ifndef __SWAP_H__
#define __SWAP_H__

void swap_int( int *, int * );

#endif // __SWAP_H__

+ swap.c

#include "swap.h"

void swap_int( int *a, int *b )
{
int tmp = *a; *a = *b; *b = tmp;
}

+ test_swap.c

#include <stdio.h>
#include "swap.h"

int main ( )
{
int a = 1, b = 100;
swap_int( &a, &b );

printf("a = %d | b = %d\n", a, b );

return 0;
}

+ test_swap.cpp

#include <iostream>
#include "swap.h"

int main( )
{
int a = 1, b = 100;
swap_int( &a, &b );

std::cout << "a = " << a
		  << "b = " << b
		  << std::endl;

return 0;
}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...