LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Compilation error while mixing C & C++ code. (http://www.linuxquestions.org/questions/programming-9/compilation-error-while-mixing-c-and-c-code-432630/)

mghiya 04-07-2006 06:04 AM

Compilation error while mixing C & C++ code.
 
Hello :Pengy: ,

I have been including the file linux/lvm.h in my cpp file but when i try to compile i get the following error:
/usr/include/linux/list.h:37: parse error before `new'
What I understand from this problem is that I am trying to include C code header in a cpp file and invoking the cpp compiler on it. As I understand, new being a keyword in C++ conflicts with the use of a variable with the same name in list.h which is included in lvm.h

Is there any workaround for this?

~Murtaza

Flesym 04-07-2006 08:28 AM

You can define the keyword 'new' as something else before including the file. But don't forget to undefine it afterwards! Something like the following sample should work:
Code:

#ifdef __cplusplus
#define new _new
#include <linux/lvm.h>
#undef new
#endif


mghiya 04-11-2006 07:20 AM

Thats what I am currently doing anyways. Any other way of doing it???

Hivemind 04-11-2006 09:45 AM

Well, you should not try to compile the C source file as C++ source file if it contains constructs that are invalid C++. Instead, compile it as C and when you include the C header in a C++ source file, do:
Code:

extern "C" {
#include "c-source-file.h"
}

This project demonstrates:
Code:

/* cpp-code.cpp */

extern "C" {
#include "c-code.h"
}

int
main()
{
  int *ptr = new int;

  c_func();

  delete ptr;
}

Code:

/* c-code.h */

#ifndef C_CODE_H
#define C_CODE_H

void c_func();

#endif /* #ifndef C_CODE_H */

Code:

/* c-code.c */

#include "c-code.h"
#include <stdio.h>

void
c_func()
{
  int new = 4711;

  printf("%i\n", new);
}

Code:

CC = gcc
CXX = g++
CFLAGS = -Wall -W -ansi -pedantic -g -O0 -c
CXXFLAGS = -Wall -W -ansi -pedantic -g -O0 -c
OBJECTS = c-code.o cpp-code.o
EXEC = runme.exe

all: $(OBJECTS)
        $(CXX) $^ -o $(EXEC)

c-code.o: c-code.c
        $(CC) $(CFLAGS) $<

cpp-code.o: cpp-code.cpp
        $(CXX) $(CXXFLAGS) $<

clean:
        rm -f $(OBJECTS) $(EXEC) *~ *.stackdump



All times are GMT -5. The time now is 05:31 AM.