-   Programming (
-   -   Compilation error while mixing C & C++ code. (

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?


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:

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

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:

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

This project demonstrates:

/* cpp-code.cpp */

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

  int *ptr = new int;


  delete ptr;


/* c-code.h */

#ifndef C_CODE_H
#define C_CODE_H

void c_func();

#endif /* #ifndef C_CODE_H */


/* c-code.c */

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

  int new = 4711;

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


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) $<

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

All times are GMT -5. The time now is 04:27 PM.